skip to Main Content

How do I get WordPress to display the result (number of all products in the shop) exactly where I want it to be. So far I have inserted the code (see below) into functions.php and the result is also displayed, but top left on all pages… I only need to display this in a special page. something like that: today we have a total of XXX products in our database.

Thanks for your support!!

My question refers to this post and i was prompted to ask a new question.
Displays the total number of products

This is the code:

'posts_per_page' => -1 );
$products = new WP_Query( $args );
echo $products->found_posts;

2

Answers


  1. This depends as how your theme is coded but one thing you could do is to the same thing but in a Shortcode, if you add something like this in your functions.php

    function total_products_func(){
        $args = array( 
          'post_type' => 'product', 
          'post_status' => 'publish', 
          'posts_per_page' => -1 
        );
        $products = new WP_Query( $args );
        return "Today we have a total of " . $products->found_posts . "products in our database";
    }
    add_shortcode( 'total_products', 'total_products_func' );
    
    

    Then in the content of the page you want to show the message just add

    [total_products]
    

    This should display the text with the total count of products

    Login or Signup to reply.
  2. You can actually simplify this using wp_count_posts().

    https://developer.wordpress.org/reference/functions/wp_count_posts/

    function total_products_func() {
        
        $count = wp_count_posts('product');
        return "Total products on hand: " .$count->publish;
    
    }
    add_shortcode( 'total_products', 'total_products_func' );
    

    However, as Pol pointed out a short code is the easiest way and could be updated to allow you to customize the message on the fly. As well, you could also even use this to easily pull total numbers for any post type you have.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search