1

I'm trying to display the product Count next to each category and child category. I'm using $category->getProductCount() but nothing is showing up.

Here is my sidebar.phtml

<?php
/**
 * Category sidebar
 *
 * @var $block Sebwite\Sidebar\Block\Sidebar
 */
$isEnabled     = $block->isEnabled();
$titleText     = $block->getTitleText();
$isOpenOnLoad  = $block->isOpenOnLoad();
$categories    = $block->getCategories();

if ($isEnabled && count($categories)>0) {
?>

    <h3><?= $titleText; ?></h3>
    <ul class="o-list">

    <?php
    // Loop through categories
    foreach ( $categories as $category ) :
        ?>
        <li class="level0<?php echo($block->isActive($category) ? ' active' : ''); ?>">
            <a href="<?php echo $block->getCategoryUrl($category); ?>" title="<?php echo $category->getName(); ?>" class="<?php echo($block->isActive($category) ? ' active' : ''); ?>">
                <?php echo $category->getName(); ?>
                <?php 
                echo $category->getProductCount();?>
            </a>
            <?php if ( $category->hasChildren() ) : ?>
                <span class="expand"><?php echo $block->isActive($category) ? '<i class="fa fa-minus"></i>' : '<i class="fa fa-plus"></i>'; ?></span>
            <?php endif; ?>

            <?php echo $block->getChildCategoryView($category); ?>
        </li>
    <?php endforeach; ?>
    </ul>
<?php if ($isOpenOnLoad) { ?>
    <script>
        require(['jquery', 'sidebarmodule'], function($) {
            $('.is-active').parents('ul').css('display','block');
            $('.is-active').parents('li').addClass('active');
            $('.is-active').parents('li').find('> span i').removeClass('fa-plus').addClass('fa-minus');
        });
    </script>
<?php } else { ?>
    <script>
        require(['jquery', 'sidebarmodule'], function($) {});
    </script>
<?php }
} ?>

1 Answer 1

1

Try this method $category->getProductCollection()->count();

2
  • It gives me a Fatal error: Uncaught Error: Call to a member function count() on null. I'm not sure what I am missing
    – Zei
    Apr 2, 2022 at 20:29
  • I think ProductCollection() returns the number of categories but not the number of products if I'm not mistaken?
    – Zei
    Apr 2, 2022 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.