Create WordPress Shortcode To Display Number Of Products

Photo of author
Written By geekerhub

Experienced WordPress developer with over 10 years of experience working with the platform

In WooCommerce, you can create a shortcode that displays the total number of products in your store by using the wc_get_product_count function. This function returns the total number of products in your store, including both published and unpublished products.

Here’s an example of how you can create a shortcode that displays the total number of products in your store:

 
 
 
Copy Code
function total_products_shortcode() {
    $total_products = wc_get_product_count();
    return $total_products;
}
add_shortcode( 'total_products', 'total_products_shortcode' );

This example creates a shortcode called total_products, which you can use in your pages and posts like this:

 
 
 
Copy Code
[total_products]

This will output the total number of products in your store.

You could also use wp_count_posts to count only the number of published products, then use the post type of product to retrieve the product count, like so:

 
 
 
Copy Code
function total_published_products_shortcode() {
    $count = wp_count_posts('product');
    return $count->publish;
}
add_shortcode( 'total_published_products', 'total_published_products_shortcode' );

In this case we are creating a shortcode called total_published_products

In both examples, the shortcodes will return a number which you can use in any way you want, like appending a message for example.

It’s worth noting that you need to place these codes in your active theme’s functions.php file or in a plugin.

Please make sure you have a backup or a version of your functions.php file before editing it.

 

Leave a Comment