显示Prestashop的Category旁边的产品数量

How to achive this:

Category 1 (899)

-- Category 1.1 (189)

-- Category 1.2 (700)

----- Category 1.2.1 (300)

----- Category 1.2.2 (400)

I have made some progess. But it onlly counts the number of products in "Subcategories"

This is the code:

$ProductsCount = 0;
    $ProductsCount = (int)Db::getInstance()->getValue('SELECT COUNT(cp.`id_product`) AS total
    FROM `'._DB_PREFIX_.'product` p
    '.Shop::addSqlAssociation('product', 'p').'
    LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON p.`id_product` = cp.`id_product`
    WHERE cp.`id_category` = '.$id_category.
    ' AND product_shop.`visibility` IN ("both", "catalog")
    AND product_shop.`active` = 1;' );

but i get such result:

Category 1 (0)

-- Category 1.1 (0)

-- Category 1.2 (0)

----- Category 1.2.1 (300)

----- Category 1.2.2 (400)

I think this code needs some modification. Or Am i wrong? I fit is more complicated then sorry for posting this here!

You should have read the source before :)

The Category::getProducts() method allows you to get the total number of product in a category. No need to write your own SQL query.

Something like this adapted to your code should work:

$category = new Category($id_category, $id_lang);
$productCount = $category->getProducts($id_lang, 1, 10000, null, null, true); // the last parameter is $get_total

Now I can't remember if the method returns the total of product including the subcategories, but looking at the method you should be able to write your own that will fit.

To count Products in Category :

Add this in /classes/Category.php

public static function countProductInCat($id_category){
    $category = new Category($id_category, 1);
    $productCount = $category->getProducts(1, 1, 10000, null, null, true);
    return $productCount;
}

And use this to display in .tpl

{Category::countProductInCat(*idCat*)}

try {$nb_products} in <h1 class="page-heading"> in theme_dir/category.tpl

Here the result: Here the result: