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


WP get first and last post title

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

<?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>';

使用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