문제

i'm using Magento 2.3.4 and i want some product URL is using different URL from URL rewrite,because i already created a custom frontend page for this product:

for example

getProductUrl() => http://baseurl.com/sku.html into getProductUrl() => http://baseurl.com/custom/product/page/id/5
도움이 되었습니까?

해결책

There are several you can do that.

Create an after plugin on \Magento\Catalog\Model\Product\Url:getProductUrl method and change function output that function.

Define di.xml location: app/code/{VendorName}/{ModuleName/etc/ and declare the plugin here from here

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Model\Product\Url">
        <plugin disabled="false" name="StackExchange_MagentoTest_Plugin_Magento_Catalog_Model_Product_Url" sortOrder="12" type="StackExchange\MagentoTest\Plugin\Magento\Catalog\Model\Product\Url"/>
    </type>
</config>

Defined plugin class

Location: app/code/{VendorName}/{ModuleNamePlugin/Magento/Catalog/Model/Product/Url.php

<?php


namespace StackExchange\MagentoTest\Plugin\Magento\Catalog\Model\Product;

class Url
{
    private $urlFactory;
    privtae $storeManager;
    
    public function __construct(
    \Magento\Framework\UrlFactory $urlFactory,
    \Magento\Store\Model\StoreManagerInterface $storeManager    
    ){
         $this->urlFactory = $urlFactory;
         $this->storeManager = $storeManager;   
    }

    public function afterGetProductUrl(
        \Magento\Catalog\Model\Product\Url $subject,
        $result,
        $product, 
        $routeParams    
    ) {
        $storeId = $product->getStoreId();
         if (isset($routeParams['_scope'])) {
            $storeId = $this->storeManager->getStore($routeParams['_scope'])->getId();
        }

        if ($storeId != $this->storeManager->getStore()->getId()) {
            $routeParams['_scope_to_url'] = true;
        }
        $routePath = 'custom/product/page/';
        $routeParams['id'] = $product->getId();
        $url = $this->urlFactory->create()->setScope($storeId);
        return $url->getUrl($routePath, $routeParams);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top