To get the current category product count
Create your own module at below location Magento_root/app/code for that create Package/Modulename
Create below files there
registration.php
etc/module.xml
Block/Blockfile.php
view/frontend/layout/module_section_page.xml
view/frontend/templates/template.phtml
Put this code in your Blockfile.php
<?php
namespace Package\Module\Block;
class Blockfile extends \Magento\Framework\View\Element\Template{
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry
) {
$this->_registry = $registry;
parent::__construct($context);
}
public function getCurrentCategory(){
$current_Category = $this->_registry->registry('current_category');
return $current_Category;
}
}
& this code in your template.phtml
<?php
$current_Category = $block->getCurrentCategory();
echo $current_Category->getName().'('.$current_Category->getProductCollection()->Count().')';
$categories = $this->getStoreCategories(true,false,true);
if($current_Category->hasChildren()){
$subCategories = $current_Category->getChildrenCategories($categories);
foreach($subCategories as $subCategory) {
echo '<li style="color:Green;"><a href="'.$subCategory->getUrl().'">'.$subCategory->getName().'(' .$subCategory->getProductCollection()->Count().')'.'</a></li>';
}
}
Run The below Command & see the changes
php bin/magento setup:upgrade
Still facing any issue feel free to revert back
Update:
It is working fine for me you can have a look
Backend:
Frontend
Note: Try to avoid the use of objectmanager into the template
files