NB: Make sure you do a back up of your theme, files and database before attempting the tutorials


---- Last modified : Sep 21 2022

Estimated reading time : 1 minute, 32 seconds - 110 words

You have created a Post Meta or Post Type called Products and now want to display the number of products with Count Post Meta or Count Post type…

Displaying the Count Post meta or Post type

First we have to look at the Post Meta. Let’s say your meta key is called votes. Add it wherever you want to display the vote count.

// On définit le Meta Key a utiliser. 
$meta_key = 'votes'; 
// On questionne la Base de données et on fait le Compte et on le place dans une variable. 
$votescount = $wpdb->get_var( $wpdb->prepare(
"SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key = %s",
echo "<span class='votescounts'>{$votescount}</span>";

Now we can use a hook that will display the exact number of your Products post type. Here’s the function to use in your functions.php file:

function theme_count_products() {
	$products = new WP_Query(array( 'post_type' => 'products' ));
	if ($products->have_posts()) {
	$count_posts = wp_count_posts('products')->publish;
	if ( $count_posts == "$count_posts" ) {
	echo "<span class='count-products'>$count_posts</span>"; }

You can use it in the template of your choice.

<?php echo theme_count_products(); ?>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>