mmdwc
mmdwc

Reputation: 1137

php display only the last result of a if loop

I'm using a loop on my website to display the previous post permalinks of a current post.

<?php
global $post;
$current_post = $post;
for($i = 1; $i <= 30; $i++):
$post = get_previous_post();
setup_postdata($post); ?>

<?php if($post): ?>

<a href="<?php the_permalink(); ?>" title="post-<?php the_ID(); ?>" class="next_link">Next Posts</a>

<?php endif; ?>
<?php endfor;
wp_reset_postdata();
$post = $current_post; 
?>

using this loop I get 30 times the "next posts" link. what I want to do, is to only get the last result of this loop.

for the moment, I'm using css and jquery to only display the last link, using this css :

a.next_link {display:none}
a.next_link:last-child {display: block}

but as you can imagine it's not a nice solution.

I would like to run the loop and only get the last $post.

is there a way adding some php to my loop to only get the last $post of this loop ?

thanks for your help,

Upvotes: 1

Views: 137

Answers (1)

Kevin Stich
Kevin Stich

Reputation: 783

What you want to do is skip the previous 29 entries, since WP doesn't provide you a way to do that out of the box. Use continue to manipulate your loop.

<?php
global $post;
$current_post = $post;
for($i = 1; $i <= 30; $i++):
$post = get_previous_post();
if ($i != 30):
  continue;
endif;
setup_postdata($post); ?>

<?php if($post): ?>

<a href="<?php the_permalink(); ?>" title="post-<?php the_ID(); ?>" class="next_link">Next Posts</a>

<?php endif; ?>
<?php endfor;
wp_reset_postdata();
$post = $current_post; 
?>

Upvotes: 1

Related Questions