Magento 2.4.3 – How to Get All Products Displayed on a Page

catalogcatalogsearchmagento2.4.3product-collectionproducts

I am trying to get all the products which are displayed on the current page. The information is used for tracking cookies on the page.ready call.

It was possible to get the product from the product page using the Registry class, on the cart and checkout pages I can use the Cart class. How can I get the currently displayed products on the catalog page?

Both classes are deprecated as I am on magento 2.4.3 .

Best Answer

If you don't have access to the $collection you can use a jQuery to parse all ids:

var productIds = [];
jQuery('.product-items').find('[id*=product-item-info_]')
    .each(function (i, e) {
        productIds[i] = parseInt(e.id.replace('product-item-info_', ''))
    });

console.log(productIds);

Result:

Result in console on category view page

But better way is to take all ids right from the product collection:

<script type="text/javascript">
    var productIds = '<?= $_productCollection->getAllIds();?>'
</script>

Magento does not use any ui-components in the standard product listing block, so they cannot be detected using the registry.

Update

You can add own block to the layout:

Vendor/Module/view/frontend/layout/catalog_category_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="category.product.list.additional">
            <block class="Vendor\Module\Block\CategoryAdditional" name="additional_products_info_js" template="Vendor_Module::products_additional_info.phtml" />
        </referenceContainer>
    </body>
</page>

Block code:

app/code/Vendor/Module/Block/CategoryAdditional.php

<?php

namespace Vendor\Module\Block;

class CategoryAdditional extends \Magento\Framework\View\Element\Template
{
    public function getCollection() {
        return $this->getLayout()->getBlock('category.products.list')->getLoadedProductCollection();
    }
}

Template where you can use the product collection to fill your javascript object (you can get a sku, name and other information right from the collection):

app/code/Vendor/Module/view/frontend/templates/products_additional_info.phtml

<?php
/** @var \Vendor\Module\Block\CategoryAdditional $block */
?>
<h3><?= __('Product ids');?></h3>
<?php
$productIds = $block->getCollection()->getAllIds();
echo implode(',', $productIds);
// Add relevant script here, it's just a sample code which will render all the ids
?>

Results (tested with standard layered navigation):

11 products:

Products 1

With filter (1 product):

Products 2