Lorie Dupont
Lorie Dupont

Reputation: 66

WP get first and last post title

I am listing cities and order them alphabetically and I came up with this code

<?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();?>

This code generates the following HTML

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

but what I am trying to achieve is to have the first and last post title next to the letter, something like this

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

How can I get in wordpress the last post title? Any ideas? Thank You.

I tried this for the first but I don't know about the last

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

Upvotes: 2

Views: 3246

Answers (1)

raam86
raam86

Reputation: 6871

Use get_posts this will get you the array of posts and you can access the data as in any array.

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

Or with WP_query:

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

Upvotes: 3

Related Questions