Is there a way to get a number of items within Wordpress loop code:
<?php while (have_posts()) : the_post(); ?>
This loop lists the posts. I need to add certain classes to first 3 depending on the total number of them.
Simply copy the [sbs_posts] shortcode and add it to any WordPress post, page, or shortcode enabled sidebar widget. It will show the total number of published posts on your WordPress site. You can also use [sbs_blog_stats] which will show all blog stats including the total number of posts.
The Loop is PHP code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags. Any HTML or PHP code in the Loop will be processed on each post.
The Loop extracts the data for each post from the WordPress database and inserts the appropriate information in place of each template tag. Any HTML or PHP code in The Loop will be processed for each post.
You can use the post_count
property of $WP_Query
, like so:
$wp_query->post_count
Be aware of the difference with found_posts
, which counts the posts which, though matching the query, are not being displayed (e.g. for pagination). You might want to use one or the other depending on your particular situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With