I have passing category id through xml i'm trying to check it in block file.but it did not work

foreach ($productCollection as $product) {
            //  get product id
    // get category // IDEA:
    $filterCats = explode(',',$this->getData('parentcat'));
    // filter bestselling products using category id
    if($filterCats != NULL){
    $collection      = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Collection')->addIdFilter($productIds)->addCategoriesFilter(array('in' => $filterCats));

     $collection      = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Collection')->addIdFilter($productIds);


  <block class="Mageplaza\Productslider\Block\BestSellerProducts" name="product.slider.bestsellerproducts" template="productslider.phtml" after="banner.block.1">
            <argument name="products_count" xsi:type="number">8</argument>
            <argument name="margin" xsi:type="string">5</argument>
          <argument name="parentcat" xsi:type="number">2</argument>
            <argument name="heading" xsi:type="string">Best Sellers</argument>
            <argument name="description" xsi:type="string">Here is your Best Sellers description </argument>
  • You need to check the condition at last after the $collection you have added. – Sukumar Gorai Sep 25 '18 at 10:57
  • if($filterCats == 0){ $collection = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Collection')->addIdFilter($productIds); } $collection = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Collection')->addIdFilter($productIds)->addCategoriesFilter(array('in' => $filterCats)); I have added like this but it won't work – Nismath vi Sep 25 '18 at 11:54

According to docks you should use


see here: https://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/xml-instructions.html (at the bottom)

It will be better for semantic if you name the parameter parent_cat and then use function: $this->getParentCat();

Let me know if it solves the problem ;)

| improve this answer | |
  • i doesn't matter it is parentcat or parent_cat it works .i want to check the condition – Nismath vi Sep 25 '18 at 10:47
  • Maybe it is a problem with addCategoriesFilter ? Did you try regular addFieldToFilter method? – Jan Żaba Sep 25 '18 at 10:51
  • yeah it works. without if condition – Nismath vi Sep 25 '18 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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