在 Shopware 产品列表页面上显示评论计数

Raj*_*ami 2 shopware shopware6 shopware6-app

我想要产品列表页面(如产品详细信息页面)上产品评论的总计数,如何在列表页面上获取该计数?

dne*_*adt 6

这并不是那么微不足道的事情。您需要编写一个插件来实现此目的。

在您的插件中,您需要创建订阅者并侦听与产品搜索和列表相关的事件。然后,您需要通过添加聚合来更改搜索条件,以及为列出的产品对象设置聚合值的搜索结果。

class CustomListingEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ProductListingCriteriaEvent::class => [
                ['handleListingCriteria', -101],
            ],
            ProductSearchCriteriaEvent::class => [
                ['handleListingCriteria', -101],
            ],
            ProductListingResultEvent::class => [
                ['handleListingResult', 0],
            ],
            ProductSearchResultEvent::class => [
                ['handleListingResult', 0],
            ],
        ];
    }

    public function handleListingCriteria(ProductListingCriteriaEvent $event): void
    {
        $criteria = $event->getCriteria();

        $criteria->addAggregation(
            new TermsAggregation('review_count', 'product.id', null, null, new CountAggregation('review_count', 'product.productReviews.id'))
        );
    }

    public function handleListingResult(ProductListingResultEvent $event): void
    {
        /** @var TermsResult $aggregation */
        foreach ($event->getResult()->getAggregations() as $aggregation) {
            if ($aggregation->getName() === 'review_count') {
                foreach ($aggregation->getBuckets() as $bucket) {
                    /** @var SalesChannelProductEntity $product */
                    $product = $event->getResult()->getEntities()->get($bucket->getKey());
                    if (!$product) {
                        continue;
                    }
                    // Ideally you should implement you own `Struct` extension
                    $text = new TextStruct();
                    $text->setContent((string) $bucket->getResult()->getCount());
                    $product->addExtension('review_count', $text);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于此示例,它将计算与产品相关的所有评论,而不仅仅是那些活跃的评论。您可能还想查看有关如何过滤聚合的文档。

之后,在产品框的模板中,您应该能够输出每个产品的评论数:

{{ product.extensions.review_count.content }}
Run Code Online (Sandbox Code Playgroud)