How to Show the Latest Products first in the list for selected Categories – Shopware 6?

How to Show the Latest Products first in the list for selected Categories – Shopware 6?

In this article, we will discuss how to show the latest products first in the list of products in a category.

We need to add a custom subscriber for ProductEvents

/**
 * class MySubscriber implements EventSubscriberInterface
{

    /**
     * @var SystemConfigService
     */
    private $systemConfigService;

    public function __construct(
        SystemConfigService $systemConfigService
    ) {
        $this->systemConfigService = $systemConfigService;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            ProductEvents::PRODUCT_LISTING_CRITERIA => 'productListingCriteria'
        ];
    }

    public function productListingCriteria(ProductListingCriteriaEvent $event)
    {
        if ($this->systemConfigService->get(Plugin.config.sortCreatedByCategories')) {
            if ($this->checkCategoryFromConfig( $this->systemConfigService->get('Plugin.config.sortCreatedByCategories'), $event->getRequest()->attributes->get('navigationId')) ) {
                $criteria = $event->getCriteria();

                $criteria->addSorting(
                    new FieldSorting('createdAt', 'DESC')
                );
            }
        }

        return;
        
         }

    function checkCategoryFromConfig($categories, $configCategory)
    {
        if(is_array($configCategory)) {
            return !empty(array_intersect($configCategory, $categories));
        }

        return !empty(in_array($configCategory, $categories));
    }
}

 */

 

Here we are using the SystemConfigService to get the plugin configuration. By using that the selected category or categories in the plugin configuration are fetched.

Then we need to sort the list by the created date.

Here are the services.xml and config.xml so it makes your life easier.

/**
 * <service id="Plugin\Subscriber\MySubscriber">
     <argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService" />
     <tag name="kernel.event_subscriber"/>
</service>
 */<span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1">​</span>
/**
 * <card>
    <component name="sw-entity-multi-id-select">
         <name>sortCreatedByCategories</name>
         <entity>category</entity>
         <label>Choose Categories To Be Sorted Based on Creation Date</label>
    </component>
</card
 */<span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1">​</span>

Hope it helps

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × 5 =

2hats Logic HelpBot