系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》
本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。
在Magento 2的类别页面上显示带有页面标题的产品计数的步骤:
步骤1:为此,请在app\Code\Vendor\Extension\etc\文件夹中创建events.xml文件,然后添加以下代码:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="layout_generate_blocks_after"> <observer instance="Vendor\Extension\Observer\Productcount" name="Vendor\Extension\Observer\Productcount"/> </event> </config>
第 2 步:接下来,在app\Code\Vendor\Extension\Observer\文件夹中创建Productcount.php并添加以下代码:
<?php
namespace Vendor\Extension\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class Productcount implements ObserverInterface
{
public function execute(Observer $observer)
{
if ($observer->getEvent()->getData('full_action_name') === 'catalog_category_view')
{
$layout = $observer->getEvent()->getData('layout');
$listBlock = $layout->getBlock('category.products.list');
$categoryViewBlock = $layout->getBlock('category.products');
$count = 0;
if ($listBlock)
{
$productCollection = $listBlock->getLoadedProductCollection();
if ($productCollection && $productCollection->count() >0)
{
$count = $productCollection->count();
}
}
if ($categoryViewBlock)
{
$currentCategory = $categoryViewBlock->getCurrentCategory();
if ($currentCategory)
{
$count = $currentCategory->getProductCollection()->count();
}
}
$pageMainTitle = $layout->getBlock('page.main.title');
if ($pageMainTitle)
{
$oldTitle =$pageMainTitle->getPageTitle();
$pageMainTitle->setPageTitle(
$oldTitle
. _(' - Product Count: ' . (int) $count)
);
}
}
}
}步骤3:最后运行以下命令:
php bin/magento cache:flush
结论:
因此,所有人都能够在Magento 2的类别页面上显示带有页面标题的产品计数。