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

Intermediate

---- Last modified : Sep 06 2022

Estimated reading time : 2 minutes, 2 seconds - 220 words

This tutorial will show you how to create a query to display all of your WooCommerce products.

First a quick explaination of found_posts which can be seen in the query below. It will allow you to filter the number of products found and matching the Posts ou Post Types inside your arguments.

For everything else, it’s a simple and basic query for WooCommerce. The post for WooCommerce products is simply called product.

Display the Number of WooCommerce Products

function via_classement_woocommerce_products_count_total() {
    $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1 );
	$products = new WP_Query( $args );
	echo '<span class="numberCircle">';
	echo $products->found_posts;
	echo '</span>';
}

Here’s how we can avoid multiplying your functions if you want to use the same function but you want to display the number of product by status:
Here are the various post_status of your posts or Post Types:
– ‘publish’ == Published
– ‘Future’ == Scheduled
– ‘Draft’ == Draft
– ‘Pending’ == Pending Review
– ‘Private’ == Private
– ‘Trash’ == Deleted

Now let’s build the previous function considering we want to display the number of products and their status.

Here’s the function to add in your functions.php file. Note that we stored a $statut variable that will allow us to fetch the value that we want to assign to it. Said value is display as such: ‘post_status’ => $statut.

function via_classement_woocommerce_products_count_total($statut) {
    $args = array( 'post_type' => 'product', 'post_status' => $statut, 'posts_per_page' => -1 );
	$products = new WP_Query( $args );
	echo '<span class="numberCircle">';
	echo $products->found_posts;
	echo '</span>';
}

Now in the desired WordPress php template file, display the function this way:

<?php echo via_classement_woocommerce_products_count_total($statut = 'publish'); ?>

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>