Jump to content

Show Product Count


HustlaOwnz

Recommended Posts

I am wanting to show the product count next to the subcategory's name, when you click on the subcategory's category.

 

I have read previous topics about this, but nothing really helps at all due to me having the newest version, 1.5.3.

 

Example:

Category = Computers

SubCategory = Dell

 

You click on 'Computers' from your category block list and it shows 'Dell' with its description.

The problem is, it just shows 'Dell'.

I want it to show 'Dell [# of products]'.

 

I figured out the basic concepts:

-I have to edit theme/category.tpl

-The code is in this block of code:

<!-- Subcategories -->
 <div id="subcategories">
  <h3>{l s='Subcategories'}</h3>
  <ul class="inline_list">
  {foreach from=$subcategories item=subcategory}
<li class="clearfix">
 {*<a href="{$link->getCategoryLink($subcategory.id_category, $subcategory.link_rewrite)|escape:'htmlall':'UTF-8'}" title="{$subcategory.name|escape:'htmlall':'UTF-8'}" class="img">
  {if $subcategory.id_image}
   <img src="{$link->getCatImageLink($subcategory.link_rewrite, $subcategory.id_image, 'medium_default')}" alt="" width="{$mediumSize.width}" height="{$mediumSize.height}" />
  {else}
   <img src="{$img_cat_dir}default-medium_default.jpg" alt="" width="{$mediumSize.width}" height="{$mediumSize.height}" />
  {/if}
 </a>*}
 <a href="{$link->getCategoryLink($subcategory.id_category, $subcategory.link_rewrite)|escape:'htmlall':'UTF-8'}" class="cat_name">{$subcategory.name|escape:'htmlall':'UTF-8'}</a>
 {if $subcategory.description}
  <p class="cat_desc">{$subcategory.description}</p>
 {/if}
</li>
  {/foreach}
  </ul>
  <br class="clear"/>
 </div>
 {/if}

 

I edited the following line of the above code:

<a href="{$link->getCategoryLink($subcategory.id_category, $subcategory.link_rewrite)|escape:'htmlall':'UTF-8'}" class="cat_name">{$subcategory.name|escape:'htmlall':'UTF-8'}</a>

 

To this:

<a href="{$link->getCategoryLink($subcategory.id_category, $subcategory.link_rewrite)|escape:'htmlall':'UTF-8'}" class="cat_name">{$subcategory.name|escape:'htmlall':'UTF-8'}</a> [{l s='%d products' sprintf=$subcategory}]

 

But obvisly the '$subcategory' is showing each subcategory's id number and I want it to show how many products are under that subcategory.

 

I also tried '{include file="$tpl_dir./category-count.tpl"}' for the subcategory's product count, but it will only count the products for the subcategory's actual category, so in my example it would show 'Computers' product count instead of 'Dells' product count in which I want it to show.

 

 

 

Please help me, I've spent hours trying to figure this out! I've seen this feature in another E-commerce solution, in which they had it as an automatic option upon installation. I was kind of disappointed to see such a common thing not included in PrestaShop, but everything else I am very satisfied with. Other than that, I'm very glad I switched to PrestaShop.

 

Any help is appreciated! :)

Edited by HustlaOwnz (see edit history)
Link to comment
Share on other sites

  • 1 month later...

Hi HustlaOwnz/marfel,

 

I have here some code for you for PS 1.5.3(.1) to add the amount of products in a (sub)category behind the category name in the category block in the left column(by default).

 

I'm not sure if it is exactly what you need yet (I see you talk about 'when clicking on' a category), but it gives you a start to play with and you can then modify as needed.

 

Open the file /module/blockcategory.php

go to function :

 

public function getTree($resultParents, $resultIds, $maxDepth, $id_category = null, $currentDepth = 0)

 

and find in this function the following 2 lines of code and then add the red code underneath these:

...

 

if (!isset($resultIds[$id_category]))

return false;

 

// added the # of products per category, so we can display these in the category tree block.

// N.B. Only the really shown products in the front office are counted, no drafts)

$ProductsCount = 0;

$ProductsCount = (int)Db::getInstance()->getValue('SELECT COUNT(cp.id_category) FROM '._DB_PREFIX_.'category_product cp, '._DB_PREFIX_.'product pr WHERE cp.id_category = '.$id_category .' AND cp.id_product = pr.id_product AND pr.active = 1' );

 

 

 

then just below the code you just added, you have a long line of code that looks like: (add the red code shown at the end)

 

 

$return = array('id' => $id_category, 'link' => $this->context->link->getCategoryLink($id_category, $resultIds[$id_category]['link_rewrite']),'name' => $resultIds[$id_category]['name'], 'desc'=> $resultIds[$id_category]['description'], 'children' => $children , 'products' => $ProductsCount);

// N.B. don't forget the comma before 'products'!

 

 

save the file.

 

Then go to and open the file

/theme/<your theme folder>/modules/blockcategories/category-tree-branch.tpl

 

(if this file doesn't exist in this location, copy it first to this place from /modules/blockcategories/category-tree-branch.tpl )

 

Here you see the following code, and add the red part:

 

 

<a href="{$node.link|escape:'htmlall':'UTF-8'}" {if isset($currentCategoryId) && $node.id == $currentCategoryId}class="selected"{/if} title="{$node.desc|escape:'htmlall':'UTF-8'}">{$node.name|escape:'htmlall':'UTF-8'}({$node.products})</a>

 

 

 

save the file.

 

Go to and Refresh your shop front page. See if it works.

 

Please reply with feedback if it works for you or not and any additional question you may have.

 

 

Hope this helped,

Pascal

 

P.S. The adjustment code I found a long time ago somewhere on this forum, but for an old version of PS (1.3.x I think).

Except for the addition of filtering out the draft products, the code credits go entirely to the original coder.

Link to comment
Share on other sites

  • 3 weeks later...

Hi - did anyone get this working? The above solution didn't work for me as the subcateory count needs to be passed through to category.tpl and it doesn't seem to be related to category-tree-branch.tpl.

 

I think it might require editing the /controllers/front/CategoryController.php file as the $subcategories variable seems to be set there. I'm not sure though.

 

Any help would be much appreciated.

Link to comment
Share on other sites

Described solution is for module Block Categories only. It works fine with 1.5.3.1 and single store. The SQL request should be extended to manage multiple stores:

$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;' );

 

If you need to display total number of products per sub-category after you selected a category, then you have to update Categories controller.

Note the following row in function assignProductList:

$this->nbProducts = $this->category->getProducts(null, null, null, $this->orderBy, $this->orderWay, true);

It retrieves number of products per selected category.

 

Now you may update CategorController function assignSubcategories to collect number of products per subcategory using the same function:

foreach ($subCategories as $key => $subcat)
{
$subcategoryObj = new Category((int)$subcat['id_category']);
$subCategories[$key]['nb_products'] = $subcategoryObj->getProducts(null, null, null, null, null, true);
}

 

In category.tpl you should add the following code to display number of products after name:

({$subcategory.nb_products})

after

{$subcategory.name|escape:'htmlall':'UTF-8'}

 

BTW, it's nice to have a separate static function to collect number of products without details in Categories class, i.e. to call the SQL request above without creating an instance and reading all useless product details.

Edited by Zhivko (see edit history)
Link to comment
Share on other sites

Hi I got this working by doing the following in v1.5.3.1:

 

In /classes/Category.php find this code:

 

public function getSubCategories($id_lang, $active = true)
{
  if (!Validate::isBool($active))
   die(Tools::displayError());
 $groups = FrontController::getCurrentCustomerGroups();
 $sql_groups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1');
 $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  SELECT c.*, cl.id_lang, cl.name, cl.description, cl.link_rewrite, cl.meta_title, cl.meta_keywords, cl.meta_description
  FROM `'._DB_PREFIX_.'category` c
  '.Shop::addSqlAssociation('category', 'c').'
  LEFT JOIN `'._DB_PREFIX_.'category_lang` cl
   ON (c.`id_category` = cl.`id_category`
   AND `id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('cl').')
  LEFT JOIN `'._DB_PREFIX_.'category_group` cg
   ON (cg.`id_category` = c.`id_category`)
  WHERE `id_parent` = '.(int)$this->id.'
   '.($active ? 'AND `active` = 1' : '').'
   AND cg.`id_group` '.$sql_groups.'
  GROUP BY c.`id_category`
  ORDER BY `level_depth` ASC, category_shop.`position` ASC
 ');
 foreach ($result as &$row)
 {
  $row['id_image'] = file_exists(_PS_CAT_IMG_DIR_.$row['id_category'].'.jpg') ? (int)$row['id_category'] : Language::getIsoById($id_lang).'-default';
  $row['legend'] = 'no picture';
 }
 return $result;
}

 

and change it to this:

 

public function getSubCategories($id_lang, $active = true)
{
  if (!Validate::isBool($active))
   die(Tools::displayError());
 $groups = FrontController::getCurrentCustomerGroups();
 $sql_groups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1');
 $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  SELECT c.*, cl.id_lang, cl.name, cl.description, cl.link_rewrite, cl.meta_title, cl.meta_keywords, cl.meta_description
  FROM `'._DB_PREFIX_.'category` c
  '.Shop::addSqlAssociation('category', 'c').'
  LEFT JOIN `'._DB_PREFIX_.'category_lang` cl
   ON (c.`id_category` = cl.`id_category`
   AND `id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('cl').')
  LEFT JOIN `'._DB_PREFIX_.'category_group` cg
   ON (cg.`id_category` = c.`id_category`)
  WHERE `id_parent` = '.(int)$this->id.'
   '.($active ? 'AND `active` = 1' : '').'
   AND cg.`id_group` '.$sql_groups.'
  GROUP BY c.`id_category`
  ORDER BY `level_depth` ASC, category_shop.`position` ASC
 ');
 foreach ($result as &$row)
 {
  $row['id_image'] = file_exists(_PS_CAT_IMG_DIR_.$row['id_category'].'.jpg') ? (int)$row['id_category'] : Language::getIsoById($id_lang).'-default';
  $row['legend'] = 'no picture';
  $categ = new Category((int)$row['id_category'], (int)$id_lang);
  $row['nbproducts'] =$categ->getProducts(NULL, NULL, NULL,  NULL,  NULL, true);
 }
 return $result;
}

 

Basically you've added this code:

 

  $categ = new Category((int)$row['id_category'], (int)$id_lang);
  $row['nbproducts'] =$categ->getProducts(NULL, NULL, NULL,  NULL,  NULL, true);

 

Then in /themes/your_theme/category.tpl use the following code inside your foreach loop {foreach from=$subcategories item=subcategory} to get the number of products:

 

{$subcategory.nbproducts}

 

Worked a treat for me!!!

 

EDIT: PS I found this here: http://www.prestashop.com/forums/topic/154373-product-count-on-subcatergories/

Edited by jpmad4it (see edit history)
Link to comment
Share on other sites

Have you tried using a call like:

 

$category = new Category(1); // Get something to test with

$nbProducts = $category->getProducts($lang_id, 0, 0, null, null, true);

 

The above function call should return the count of products in a category ;)

Link to comment
Share on other sites

  • 4 years later...
  • 11 months later...
  • razaro changed the title to Show Product Count

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...