2

I have a simple loop for a JS slider, I want to display previous and next posts titles on my slide, but I can't get previous post title on the first slide (because apparently first post have no previous posts):

$prev_post = $loop->posts[$loop->current_post - 1]; // ALWAYS NULL FOR FIRST POST :(
$next_post = $loop->posts[$loop->current_post + 1]; // ALWAYS NULL FOR THE LAST POST
echo $next_post->post_title;
echo $next_post->post_title; 

Is there any easy way to fix that?

1
  • So what do you expect to get?
    – kraftner
    Commented Jun 7, 2014 at 15:18

1 Answer 1

3

You can loop the slides quite simply:

$prev_index = ( $loop->current_post == 0 ) ? count( $loop->posts ) - 1 : $loop->current_post - 1;
$next_index = ( $loop->current_post == count( $loop->posts ) - 1 ) ? 0 : $loop->current_post + 1;

$prev_post = $loop->posts[ $prev_index ];
$next_post = $loop->posts[ $next_index ];

echo $next_post->post_title;
echo $next_post->post_title;

This takes the last post for the previous post if the current post is the first post, and the first post for the next post if the current post is the last post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.