WP获得第一个和最后一个帖子标题

时间:2013-08-24 23:05:38

标签: php wordpress loops

我列出城市并按字母顺序排序,我想出了这段代码

<?php
$args = array(
    'post_type'        => 'cities',
    'orderby'          => 'title',
    'order'            => 'ASC',
    'posts_per_page'   => -1,
    'caller_get_posts' => 1
);
$my_query = new WP_Query($args);

if ($my_query->have_posts()) {
    while ($my_query->have_posts()) : $my_query->the_post();?>
        <?php
        $this_char = strtoupper(substr($post->post_title, 0, 1));
        if ($this_char != $last_char) {
            $last_char = $this_char;
            if (isset($flag))
                echo '</div>';
            echo '<div data-role="collapsible" class="excerpts">';
            echo '<h3 class="alphabet">' . '<div>' . $last_char . '</div>' . '</h3>';
            $flag = true;
        } ?>

        <p class="inner"><a data-transition="slide"
                            href="<?php the_permalink() ?>" rel="bookmark"
                            title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
        </p>
    <?php endwhile;
}
if (isset($flag))
    echo '</div>';

wp_reset_query();?>

此代码生成以下HTML

<div class="collapsible">
    <h3><div>A</div></h3>
    <p>Atlanta</p>
    <p>Alabama</p>
    <p>Arizona</p>
</div>

但我想要实现的是在信件旁边有第一个和最后一个帖子标题,就像这样

<div class="collapsible">
    <h3><div>A</div> Atlanta - Arizona</h3>
    <p>Atlanta</p>
    <p>Alabama</p>
    <p>Arizona</p>
</div>

我如何才能获得wordpress的最后一个帖子?有任何想法吗?谢谢。

我第一次尝试了这个,但我不知道最后一次

echo '<h3 class="alphabet">'. '<div>'.$last_char. '</div>' .  get_the_title() .' - get_the_last_title' .'</h3>';

1 个答案:

答案 0 :(得分:1)

使用get_posts这将获得一系列帖子,您可以像访问任何数组一样访问数据。

<?php 
$posts_array = get_posts( $args );
echo $posts_array[0] // First posts;
echo $posts_array[count($posts_array) -1 ] //Last Posts
?> 

或者使用WP_query:

$firstPost = $my_query -> $posts[0] // first post
$lastPost  $my_query -> $posts[$my_query->$found_posts] // Last post
相关问题