Jeffery Moore
Member
Posted 2 years ago #
I would think this topic would come up all the time, but I'm not seeing any answers searching Google or these forums. All I want to do is find a way to conditionally execute certain code if the loop has hit the last post available. For example:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php
the_content('Read the rest of this post >');
if (!last_post()) {
echo "<hr />";
}
?>
<?php endwhile; endif; ?>
The last_post() function does not exist; it is what I am looking for a way to write. All this would accomplish is to exclude the horizontal divider from the very bottom of the page. Anyone have any ideas??
Would this work?
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish'
);
$total_posts = count(get_posts($args));
$n=0;
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php
$n++;
the_content('Read the rest of this post >');
if ($n < $total_posts) echo "<hr />";
?>
<?php endwhile; endif; ?>
Jeffery Moore
Member
Posted 2 years ago #
BRILLIANT! (in the Red Bull guy voice) It works like a charm, thank you for you excellence, esmi!
Jeffery Moore
Member
Posted 2 years ago #
Only other concern I have would be...
This seems to work only when you have less posts than what you have set your 'limit per page' value to. If I could retrieve this number with PHP code, I know how to easily solve the problem. Googling returns hundreds of matches regarding simply setting this value in the GUI. haha
Any ideas?
Jeffery Moore
Member
Posted 2 years ago #
I figured out a way to get this value. I put this code above my main loop:
//get number of posts allowed per page
$posts_per_page = 0;
while (have_posts()) {
the_post();
$posts_per_page++;
}
rewind_posts();
There are probably simpler ways, but this one works for me!
Jeffery Moore
Member
Posted 2 years ago #
Just one more bit to add to this.
I had started testing my blog with more entries, but, once I got more than 5 posts added, the count() function call above would always return the number 5 no matter how many actually were there.
I looked it up and this was because there is an argument called 'numberposts' whose default value is 5 (for some reason). Setting it to -1 fixes the issue by removing any limit in the number of posts returned by get_posts().