Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress loop - how to count items

Tags:

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.

like image 841
tepad.no Avatar asked Oct 10 '13 18:10

tepad.no


People also ask

How do I count the number of posts in WordPress?

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.

How do I create a loop in WordPress?

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.

What is the loop used to do in WordPress?

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.


1 Answers

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.

like image 82
Sunyatasattva Avatar answered Oct 14 '22 16:10

Sunyatasattva