Magento 2.2.6 how we can add custom prefix in product URL?
Can anyone help me I want to add custom prefix in product url?
magento2
add a comment |
Can anyone help me I want to add custom prefix in product url?
magento2
add a comment |
Can anyone help me I want to add custom prefix in product url?
magento2
Can anyone help me I want to add custom prefix in product url?
magento2
magento2
asked 6 hours ago
Anurag RanaAnurag Rana
1612
1612
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
To add something like:
www.example.com/product-prefix/product1.html
You need to override two files in my custom module, One is Product Url Model and Another one is Router ControllerRouter
in di.xml
<preference for="MagentoCatalogModelProductUrl" type="VendorModuleNameModelUrl" />
<preference for="MagentoUrlRewriteControllerRouter" type="VendorModuleNameControllerRouter" />
in Url.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Product Url model
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace VendorModuleNameModel;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
class Url extends MagentoCatalogModelProductUrl
{
/**
* URL instance
*
* @var MagentoFrameworkUrlFactory
*/
protected $urlFactory;
/**
* @var MagentoFrameworkFilterFilterManager
*/
protected $filter;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkSessionSidResolverInterface
*/
protected $sidResolver;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkUrlFactory $urlFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilterFilterManager $filter
* @param MagentoFrameworkSessionSidResolverInterface $sidResolver
* @param UrlFinderInterface $urlFinder
* @param array $data
*/
public function __construct(
MagentoFrameworkUrlFactory $urlFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilterFilterManager $filter,
MagentoFrameworkSessionSidResolverInterface $sidResolver,
UrlFinderInterface $urlFinder,
array $data =
) {
parent::__construct($urlFactory, $storeManager, $filter, $sidResolver, $urlFinder, $data);
$this->urlFactory = $urlFactory;
$this->storeManager = $storeManager;
$this->filter = $filter;
$this->sidResolver = $sidResolver;
$this->urlFinder = $urlFinder;
}
/**
* Retrieve URL Instance
*
* @return MagentoFrameworkUrlInterface
*/
private function getUrlInstance()
{
return $this->urlFactory->create();
}
/**
* Retrieve URL in current store
*
* @param MagentoCatalogModelProduct $product
* @param array $params the URL route params
* @return string
*/
public function getUrlInStore(MagentoCatalogModelProduct $product, $params = )
{
$params['_scope_to_url'] = true;
return $this->getUrl($product, $params);
}
/**
* Retrieve Product URL
*
* @param MagentoCatalogModelProduct $product
* @param bool $useSid forced SID mode
* @return string
*/
public function getProductUrl($product, $useSid = null)
{
if ($useSid === null) {
$useSid = $this->sidResolver->getUseSessionInUrl();
}
$params = ;
if (!$useSid) {
$params['_nosid'] = true;
}
return $this->getUrl($product, $params);
}
/**
* Format Key for URL
*
* @param string $str
* @return string
*/
public function formatUrlKey($str)
{
return $this->filter->translitUrl($str);
}
/**
* Retrieve Product URL using UrlDataObject
*
* @param MagentoCatalogModelProduct $product
* @param array $params
* @return string
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getUrl(MagentoCatalogModelProduct $product, $params = )
{
$routePath = '';
$routeParams = $params;
$storeId = $product->getStoreId();
$categoryId = null;
if (!isset($params['_ignore_category']) && $product->getCategoryId() && !$product->getDoNotUseCategoryId()) {
$categoryId = $product->getCategoryId();
}
if ($product->hasUrlDataObject()) {
$requestPath = $product->getUrlDataObject()->getUrlRewrite();
$routeParams['_scope'] = $product->getUrlDataObject()->getStoreId();
} else {
$requestPath = $product->getRequestPath();
if (empty($requestPath) && $requestPath !== false) {
$filterData = [
UrlRewrite::ENTITY_ID => $product->getId(),
UrlRewrite::ENTITY_TYPE => MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::STORE_ID => $storeId,
];
if ($categoryId) {
$filterData[UrlRewrite::METADATA]['category_id'] = $categoryId;
}
$rewrite = $this->urlFinder->findOneByData($filterData);
if ($rewrite) {
$requestPath = $rewrite->getRequestPath();
$product->setRequestPath($requestPath);
} else {
$product->setRequestPath(false);
}
}
}
if (isset($routeParams['_scope'])) {
$storeId = $this->storeManager->getStore($routeParams['_scope'])->getId();
}
if ($storeId != $this->storeManager->getStore()->getId()) {
$routeParams['_scope_to_url'] = true;
}
if (!empty($requestPath)) {
$routeParams['_direct'] = $requestPath;
} else {
$routePath = 'catalog/product/view';
$routeParams['id'] = $product->getId();
$routeParams['s'] = $product->getUrlKey();
if ($categoryId) {
$routeParams['category'] = $categoryId;
}
}
// reset cached URL instance GET query params
if (!isset($routeParams['_query'])) {
$routeParams['_query'] = ;
}
$baseUrl = $this->storeManager->getStore()->getBaseUrl();
$productUrl = $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
$remainingUrl = str_replace($baseUrl, '', $productUrl);
$productUrl = $baseUrl."your-static-prefix/" . $remainingUrl;
//return $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
return $productUrl;
}
}
in Controller Router.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameController;
use MagentoUrlRewriteControllerAdminhtmlUrlRewrite;
use MagentoUrlRewriteModelOptionProvider;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
/**
* UrlRewrite Controller Router
*/
class Router implements MagentoFrameworkAppRouterInterface
{
/** var MagentoFrameworkAppActionFactory */
protected $actionFactory;
/** @var MagentoFrameworkUrlInterface */
protected $url;
/** @var MagentoStoreModelStoreManagerInterface */
protected $storeManager;
/** @var MagentoFrameworkAppResponseInterface */
protected $response;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkAppActionFactory $actionFactory
* @param MagentoFrameworkUrlInterface $url
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkAppResponseInterface $response
* @param UrlFinderInterface $urlFinder
*/
public function __construct(
MagentoFrameworkAppActionFactory $actionFactory,
MagentoFrameworkUrlInterface $url,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkAppResponseInterface $response,
UrlFinderInterface $urlFinder
) {
$this->actionFactory = $actionFactory;
$this->url = $url;
$this->storeManager = $storeManager;
$this->response = $response;
$this->urlFinder = $urlFinder;
}
/**
* Match corresponding URL Rewrite and modify request
*
* @param MagentoFrameworkAppRequestInterface $request
* @return MagentoFrameworkAppActionInterface|null
*/
public function match(MagentoFrameworkAppRequestInterface $request)
{
if ($fromStore = $request->getParam('___from_store')) {
$oldStoreId = $this->storeManager->getStore($fromStore)->getId();
$oldRewrite = $this->getRewrite($request->getPathInfo(), $oldStoreId);
if ($oldRewrite) {
$rewrite = $this->urlFinder->findOneByData(
[
UrlRewrite::ENTITY_TYPE => $oldRewrite->getEntityType(),
UrlRewrite::ENTITY_ID => $oldRewrite->getEntityId(),
UrlRewrite::STORE_ID => $this->storeManager->getStore()->getId(),
UrlRewrite::IS_AUTOGENERATED => 1,
]
);
if ($rewrite && $rewrite->getRequestPath() !== $oldRewrite->getRequestPath()) {
return $this->redirect($request, $rewrite->getRequestPath(), OptionProvider::TEMPORARY);
}
}
}
//Below i have replaced static prefix
$replaceUrl = str_replace("your-static-prefix/", "", $request->getPathInfo());
$rewrite = $this->getRewrite($replaceUrl, $this->storeManager->getStore()->getId());
//$rewrite = $this->getRewrite($request->getPathInfo(), $this->storeManager->getStore()->getId());
// CODE FOR CATEGORY REWRITE
if ($rewrite === null)
{
$pathInfo = $request->getPathInfo();
$pathInfoArray = explode("/", $pathInfo);
$key = "";
if(!empty(trim($pathInfoArray[count($pathInfoArray) - 1])))
$key = trim($pathInfoArray[count($pathInfoArray) - 1]);
elseif(!empty(trim($pathInfoArray[count($pathInfoArray) - 2])))
$key = trim($pathInfoArray[count($pathInfoArray) - 2]);
if($key != "")
{
$objectManaer = MagentoFrameworkAppObjectManager::getInstance();
$category = $objectManaer->create('MagentoCatalogModelCategory');
$collection = $category->getCollection()->addAttributeToFilter('url_key', ['like' => '%' . $key . '%']);
if($collection->count())
{
$category = $collection->getFirstItem();
$path = $category->getPath();
$pathArray = explode("/", $category->getPath());
foreach(['1', '2', $category->getId()] as $del_val)
{
if (($categoryId = array_search($del_val, $pathArray)) !== false) {
unset($pathArray[$categoryId]);
}
}
$keyArray = ;
if(count($pathArray))
{
foreach($pathArray as $pathId)
{
$pathCategory = $objectManaer->create('MagentoCatalogModelCategory')->load($pathId);
$keyArray = $pathCategory->getUrlKey();
}
}
$keyArray = $category->getUrlKey();
$key = implode("/", $keyArray);
$key = '/' . $key;
$rewrite = $this->getRewrite($key, $this->storeManager->getStore()->getId());
}
}
}
if ($rewrite === null) {
return null;
}
if ($rewrite->getRedirectType()) {
return $this->processRedirect($request, $rewrite);
}
$request->setAlias(MagentoFrameworkUrlInterface::REWRITE_REQUEST_PATH_ALIAS, $rewrite->getRequestPath());
$request->setPathInfo('/' . $rewrite->getTargetPath());
return $this->actionFactory->create('MagentoFrameworkAppActionForward');
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param UrlRewrite $rewrite
* @return MagentoFrameworkAppActionInterface|null
*/
protected function processRedirect($request, $rewrite)
{
$target = $rewrite->getTargetPath();
if ($rewrite->getEntityType() !== Rewrite::ENTITY_TYPE_CUSTOM
|| ($prefix = substr($target, 0, 6)) !== 'http:/' && $prefix !== 'https:'
) {
$target = $this->url->getUrl('', ['_direct' => $target]);
}
return $this->redirect($request, $target, $rewrite->getRedirectType());
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param string $url
* @param int $code
* @return MagentoFrameworkAppActionInterface
*/
protected function redirect($request, $url, $code)
{
$this->response->setRedirect($url, $code);
$request->setDispatched(true);
return $this->actionFactory->create('MagentoFrameworkAppActionRedirect');
}
/**
* @param string $requestPath
* @param int $storeId
* @return UrlRewrite|null
*/
protected function getRewrite($requestPath, $storeId)
{
return $this->urlFinder->findOneByData([
UrlRewrite::REQUEST_PATH => trim($requestPath, '/'),
UrlRewrite::STORE_ID => $storeId,
]);
}
}
Reference: Magento 2 .2 - How to add Static Product Prefix to Product Url?
Thanks for your quick response, I did the same way but its not working for me. Please suggest
– Anurag Rana
6 hours ago
Did you ran full deployment script after doing this?
– Shoaib Munir
6 hours ago
Yes I did both upgrade and deploy.
– Anurag Rana
6 hours ago
In my case I don't need category path in the product URL for the same I have disabled from backend and its working fine. Now I need to add custom prefix in the same URl like example.com/custom-prefix/product.html which I tried with your solution but its not working for me not sure If I missed anything.
– Anurag Rana
6 hours ago
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "479"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f260746%2fmagento-2-2-6-how-we-can-add-custom-prefix-in-product-url%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
To add something like:
www.example.com/product-prefix/product1.html
You need to override two files in my custom module, One is Product Url Model and Another one is Router ControllerRouter
in di.xml
<preference for="MagentoCatalogModelProductUrl" type="VendorModuleNameModelUrl" />
<preference for="MagentoUrlRewriteControllerRouter" type="VendorModuleNameControllerRouter" />
in Url.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Product Url model
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace VendorModuleNameModel;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
class Url extends MagentoCatalogModelProductUrl
{
/**
* URL instance
*
* @var MagentoFrameworkUrlFactory
*/
protected $urlFactory;
/**
* @var MagentoFrameworkFilterFilterManager
*/
protected $filter;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkSessionSidResolverInterface
*/
protected $sidResolver;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkUrlFactory $urlFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilterFilterManager $filter
* @param MagentoFrameworkSessionSidResolverInterface $sidResolver
* @param UrlFinderInterface $urlFinder
* @param array $data
*/
public function __construct(
MagentoFrameworkUrlFactory $urlFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilterFilterManager $filter,
MagentoFrameworkSessionSidResolverInterface $sidResolver,
UrlFinderInterface $urlFinder,
array $data =
) {
parent::__construct($urlFactory, $storeManager, $filter, $sidResolver, $urlFinder, $data);
$this->urlFactory = $urlFactory;
$this->storeManager = $storeManager;
$this->filter = $filter;
$this->sidResolver = $sidResolver;
$this->urlFinder = $urlFinder;
}
/**
* Retrieve URL Instance
*
* @return MagentoFrameworkUrlInterface
*/
private function getUrlInstance()
{
return $this->urlFactory->create();
}
/**
* Retrieve URL in current store
*
* @param MagentoCatalogModelProduct $product
* @param array $params the URL route params
* @return string
*/
public function getUrlInStore(MagentoCatalogModelProduct $product, $params = )
{
$params['_scope_to_url'] = true;
return $this->getUrl($product, $params);
}
/**
* Retrieve Product URL
*
* @param MagentoCatalogModelProduct $product
* @param bool $useSid forced SID mode
* @return string
*/
public function getProductUrl($product, $useSid = null)
{
if ($useSid === null) {
$useSid = $this->sidResolver->getUseSessionInUrl();
}
$params = ;
if (!$useSid) {
$params['_nosid'] = true;
}
return $this->getUrl($product, $params);
}
/**
* Format Key for URL
*
* @param string $str
* @return string
*/
public function formatUrlKey($str)
{
return $this->filter->translitUrl($str);
}
/**
* Retrieve Product URL using UrlDataObject
*
* @param MagentoCatalogModelProduct $product
* @param array $params
* @return string
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getUrl(MagentoCatalogModelProduct $product, $params = )
{
$routePath = '';
$routeParams = $params;
$storeId = $product->getStoreId();
$categoryId = null;
if (!isset($params['_ignore_category']) && $product->getCategoryId() && !$product->getDoNotUseCategoryId()) {
$categoryId = $product->getCategoryId();
}
if ($product->hasUrlDataObject()) {
$requestPath = $product->getUrlDataObject()->getUrlRewrite();
$routeParams['_scope'] = $product->getUrlDataObject()->getStoreId();
} else {
$requestPath = $product->getRequestPath();
if (empty($requestPath) && $requestPath !== false) {
$filterData = [
UrlRewrite::ENTITY_ID => $product->getId(),
UrlRewrite::ENTITY_TYPE => MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::STORE_ID => $storeId,
];
if ($categoryId) {
$filterData[UrlRewrite::METADATA]['category_id'] = $categoryId;
}
$rewrite = $this->urlFinder->findOneByData($filterData);
if ($rewrite) {
$requestPath = $rewrite->getRequestPath();
$product->setRequestPath($requestPath);
} else {
$product->setRequestPath(false);
}
}
}
if (isset($routeParams['_scope'])) {
$storeId = $this->storeManager->getStore($routeParams['_scope'])->getId();
}
if ($storeId != $this->storeManager->getStore()->getId()) {
$routeParams['_scope_to_url'] = true;
}
if (!empty($requestPath)) {
$routeParams['_direct'] = $requestPath;
} else {
$routePath = 'catalog/product/view';
$routeParams['id'] = $product->getId();
$routeParams['s'] = $product->getUrlKey();
if ($categoryId) {
$routeParams['category'] = $categoryId;
}
}
// reset cached URL instance GET query params
if (!isset($routeParams['_query'])) {
$routeParams['_query'] = ;
}
$baseUrl = $this->storeManager->getStore()->getBaseUrl();
$productUrl = $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
$remainingUrl = str_replace($baseUrl, '', $productUrl);
$productUrl = $baseUrl."your-static-prefix/" . $remainingUrl;
//return $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
return $productUrl;
}
}
in Controller Router.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameController;
use MagentoUrlRewriteControllerAdminhtmlUrlRewrite;
use MagentoUrlRewriteModelOptionProvider;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
/**
* UrlRewrite Controller Router
*/
class Router implements MagentoFrameworkAppRouterInterface
{
/** var MagentoFrameworkAppActionFactory */
protected $actionFactory;
/** @var MagentoFrameworkUrlInterface */
protected $url;
/** @var MagentoStoreModelStoreManagerInterface */
protected $storeManager;
/** @var MagentoFrameworkAppResponseInterface */
protected $response;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkAppActionFactory $actionFactory
* @param MagentoFrameworkUrlInterface $url
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkAppResponseInterface $response
* @param UrlFinderInterface $urlFinder
*/
public function __construct(
MagentoFrameworkAppActionFactory $actionFactory,
MagentoFrameworkUrlInterface $url,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkAppResponseInterface $response,
UrlFinderInterface $urlFinder
) {
$this->actionFactory = $actionFactory;
$this->url = $url;
$this->storeManager = $storeManager;
$this->response = $response;
$this->urlFinder = $urlFinder;
}
/**
* Match corresponding URL Rewrite and modify request
*
* @param MagentoFrameworkAppRequestInterface $request
* @return MagentoFrameworkAppActionInterface|null
*/
public function match(MagentoFrameworkAppRequestInterface $request)
{
if ($fromStore = $request->getParam('___from_store')) {
$oldStoreId = $this->storeManager->getStore($fromStore)->getId();
$oldRewrite = $this->getRewrite($request->getPathInfo(), $oldStoreId);
if ($oldRewrite) {
$rewrite = $this->urlFinder->findOneByData(
[
UrlRewrite::ENTITY_TYPE => $oldRewrite->getEntityType(),
UrlRewrite::ENTITY_ID => $oldRewrite->getEntityId(),
UrlRewrite::STORE_ID => $this->storeManager->getStore()->getId(),
UrlRewrite::IS_AUTOGENERATED => 1,
]
);
if ($rewrite && $rewrite->getRequestPath() !== $oldRewrite->getRequestPath()) {
return $this->redirect($request, $rewrite->getRequestPath(), OptionProvider::TEMPORARY);
}
}
}
//Below i have replaced static prefix
$replaceUrl = str_replace("your-static-prefix/", "", $request->getPathInfo());
$rewrite = $this->getRewrite($replaceUrl, $this->storeManager->getStore()->getId());
//$rewrite = $this->getRewrite($request->getPathInfo(), $this->storeManager->getStore()->getId());
// CODE FOR CATEGORY REWRITE
if ($rewrite === null)
{
$pathInfo = $request->getPathInfo();
$pathInfoArray = explode("/", $pathInfo);
$key = "";
if(!empty(trim($pathInfoArray[count($pathInfoArray) - 1])))
$key = trim($pathInfoArray[count($pathInfoArray) - 1]);
elseif(!empty(trim($pathInfoArray[count($pathInfoArray) - 2])))
$key = trim($pathInfoArray[count($pathInfoArray) - 2]);
if($key != "")
{
$objectManaer = MagentoFrameworkAppObjectManager::getInstance();
$category = $objectManaer->create('MagentoCatalogModelCategory');
$collection = $category->getCollection()->addAttributeToFilter('url_key', ['like' => '%' . $key . '%']);
if($collection->count())
{
$category = $collection->getFirstItem();
$path = $category->getPath();
$pathArray = explode("/", $category->getPath());
foreach(['1', '2', $category->getId()] as $del_val)
{
if (($categoryId = array_search($del_val, $pathArray)) !== false) {
unset($pathArray[$categoryId]);
}
}
$keyArray = ;
if(count($pathArray))
{
foreach($pathArray as $pathId)
{
$pathCategory = $objectManaer->create('MagentoCatalogModelCategory')->load($pathId);
$keyArray = $pathCategory->getUrlKey();
}
}
$keyArray = $category->getUrlKey();
$key = implode("/", $keyArray);
$key = '/' . $key;
$rewrite = $this->getRewrite($key, $this->storeManager->getStore()->getId());
}
}
}
if ($rewrite === null) {
return null;
}
if ($rewrite->getRedirectType()) {
return $this->processRedirect($request, $rewrite);
}
$request->setAlias(MagentoFrameworkUrlInterface::REWRITE_REQUEST_PATH_ALIAS, $rewrite->getRequestPath());
$request->setPathInfo('/' . $rewrite->getTargetPath());
return $this->actionFactory->create('MagentoFrameworkAppActionForward');
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param UrlRewrite $rewrite
* @return MagentoFrameworkAppActionInterface|null
*/
protected function processRedirect($request, $rewrite)
{
$target = $rewrite->getTargetPath();
if ($rewrite->getEntityType() !== Rewrite::ENTITY_TYPE_CUSTOM
|| ($prefix = substr($target, 0, 6)) !== 'http:/' && $prefix !== 'https:'
) {
$target = $this->url->getUrl('', ['_direct' => $target]);
}
return $this->redirect($request, $target, $rewrite->getRedirectType());
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param string $url
* @param int $code
* @return MagentoFrameworkAppActionInterface
*/
protected function redirect($request, $url, $code)
{
$this->response->setRedirect($url, $code);
$request->setDispatched(true);
return $this->actionFactory->create('MagentoFrameworkAppActionRedirect');
}
/**
* @param string $requestPath
* @param int $storeId
* @return UrlRewrite|null
*/
protected function getRewrite($requestPath, $storeId)
{
return $this->urlFinder->findOneByData([
UrlRewrite::REQUEST_PATH => trim($requestPath, '/'),
UrlRewrite::STORE_ID => $storeId,
]);
}
}
Reference: Magento 2 .2 - How to add Static Product Prefix to Product Url?
Thanks for your quick response, I did the same way but its not working for me. Please suggest
– Anurag Rana
6 hours ago
Did you ran full deployment script after doing this?
– Shoaib Munir
6 hours ago
Yes I did both upgrade and deploy.
– Anurag Rana
6 hours ago
In my case I don't need category path in the product URL for the same I have disabled from backend and its working fine. Now I need to add custom prefix in the same URl like example.com/custom-prefix/product.html which I tried with your solution but its not working for me not sure If I missed anything.
– Anurag Rana
6 hours ago
add a comment |
To add something like:
www.example.com/product-prefix/product1.html
You need to override two files in my custom module, One is Product Url Model and Another one is Router ControllerRouter
in di.xml
<preference for="MagentoCatalogModelProductUrl" type="VendorModuleNameModelUrl" />
<preference for="MagentoUrlRewriteControllerRouter" type="VendorModuleNameControllerRouter" />
in Url.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Product Url model
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace VendorModuleNameModel;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
class Url extends MagentoCatalogModelProductUrl
{
/**
* URL instance
*
* @var MagentoFrameworkUrlFactory
*/
protected $urlFactory;
/**
* @var MagentoFrameworkFilterFilterManager
*/
protected $filter;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkSessionSidResolverInterface
*/
protected $sidResolver;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkUrlFactory $urlFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilterFilterManager $filter
* @param MagentoFrameworkSessionSidResolverInterface $sidResolver
* @param UrlFinderInterface $urlFinder
* @param array $data
*/
public function __construct(
MagentoFrameworkUrlFactory $urlFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilterFilterManager $filter,
MagentoFrameworkSessionSidResolverInterface $sidResolver,
UrlFinderInterface $urlFinder,
array $data =
) {
parent::__construct($urlFactory, $storeManager, $filter, $sidResolver, $urlFinder, $data);
$this->urlFactory = $urlFactory;
$this->storeManager = $storeManager;
$this->filter = $filter;
$this->sidResolver = $sidResolver;
$this->urlFinder = $urlFinder;
}
/**
* Retrieve URL Instance
*
* @return MagentoFrameworkUrlInterface
*/
private function getUrlInstance()
{
return $this->urlFactory->create();
}
/**
* Retrieve URL in current store
*
* @param MagentoCatalogModelProduct $product
* @param array $params the URL route params
* @return string
*/
public function getUrlInStore(MagentoCatalogModelProduct $product, $params = )
{
$params['_scope_to_url'] = true;
return $this->getUrl($product, $params);
}
/**
* Retrieve Product URL
*
* @param MagentoCatalogModelProduct $product
* @param bool $useSid forced SID mode
* @return string
*/
public function getProductUrl($product, $useSid = null)
{
if ($useSid === null) {
$useSid = $this->sidResolver->getUseSessionInUrl();
}
$params = ;
if (!$useSid) {
$params['_nosid'] = true;
}
return $this->getUrl($product, $params);
}
/**
* Format Key for URL
*
* @param string $str
* @return string
*/
public function formatUrlKey($str)
{
return $this->filter->translitUrl($str);
}
/**
* Retrieve Product URL using UrlDataObject
*
* @param MagentoCatalogModelProduct $product
* @param array $params
* @return string
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getUrl(MagentoCatalogModelProduct $product, $params = )
{
$routePath = '';
$routeParams = $params;
$storeId = $product->getStoreId();
$categoryId = null;
if (!isset($params['_ignore_category']) && $product->getCategoryId() && !$product->getDoNotUseCategoryId()) {
$categoryId = $product->getCategoryId();
}
if ($product->hasUrlDataObject()) {
$requestPath = $product->getUrlDataObject()->getUrlRewrite();
$routeParams['_scope'] = $product->getUrlDataObject()->getStoreId();
} else {
$requestPath = $product->getRequestPath();
if (empty($requestPath) && $requestPath !== false) {
$filterData = [
UrlRewrite::ENTITY_ID => $product->getId(),
UrlRewrite::ENTITY_TYPE => MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::STORE_ID => $storeId,
];
if ($categoryId) {
$filterData[UrlRewrite::METADATA]['category_id'] = $categoryId;
}
$rewrite = $this->urlFinder->findOneByData($filterData);
if ($rewrite) {
$requestPath = $rewrite->getRequestPath();
$product->setRequestPath($requestPath);
} else {
$product->setRequestPath(false);
}
}
}
if (isset($routeParams['_scope'])) {
$storeId = $this->storeManager->getStore($routeParams['_scope'])->getId();
}
if ($storeId != $this->storeManager->getStore()->getId()) {
$routeParams['_scope_to_url'] = true;
}
if (!empty($requestPath)) {
$routeParams['_direct'] = $requestPath;
} else {
$routePath = 'catalog/product/view';
$routeParams['id'] = $product->getId();
$routeParams['s'] = $product->getUrlKey();
if ($categoryId) {
$routeParams['category'] = $categoryId;
}
}
// reset cached URL instance GET query params
if (!isset($routeParams['_query'])) {
$routeParams['_query'] = ;
}
$baseUrl = $this->storeManager->getStore()->getBaseUrl();
$productUrl = $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
$remainingUrl = str_replace($baseUrl, '', $productUrl);
$productUrl = $baseUrl."your-static-prefix/" . $remainingUrl;
//return $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
return $productUrl;
}
}
in Controller Router.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameController;
use MagentoUrlRewriteControllerAdminhtmlUrlRewrite;
use MagentoUrlRewriteModelOptionProvider;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
/**
* UrlRewrite Controller Router
*/
class Router implements MagentoFrameworkAppRouterInterface
{
/** var MagentoFrameworkAppActionFactory */
protected $actionFactory;
/** @var MagentoFrameworkUrlInterface */
protected $url;
/** @var MagentoStoreModelStoreManagerInterface */
protected $storeManager;
/** @var MagentoFrameworkAppResponseInterface */
protected $response;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkAppActionFactory $actionFactory
* @param MagentoFrameworkUrlInterface $url
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkAppResponseInterface $response
* @param UrlFinderInterface $urlFinder
*/
public function __construct(
MagentoFrameworkAppActionFactory $actionFactory,
MagentoFrameworkUrlInterface $url,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkAppResponseInterface $response,
UrlFinderInterface $urlFinder
) {
$this->actionFactory = $actionFactory;
$this->url = $url;
$this->storeManager = $storeManager;
$this->response = $response;
$this->urlFinder = $urlFinder;
}
/**
* Match corresponding URL Rewrite and modify request
*
* @param MagentoFrameworkAppRequestInterface $request
* @return MagentoFrameworkAppActionInterface|null
*/
public function match(MagentoFrameworkAppRequestInterface $request)
{
if ($fromStore = $request->getParam('___from_store')) {
$oldStoreId = $this->storeManager->getStore($fromStore)->getId();
$oldRewrite = $this->getRewrite($request->getPathInfo(), $oldStoreId);
if ($oldRewrite) {
$rewrite = $this->urlFinder->findOneByData(
[
UrlRewrite::ENTITY_TYPE => $oldRewrite->getEntityType(),
UrlRewrite::ENTITY_ID => $oldRewrite->getEntityId(),
UrlRewrite::STORE_ID => $this->storeManager->getStore()->getId(),
UrlRewrite::IS_AUTOGENERATED => 1,
]
);
if ($rewrite && $rewrite->getRequestPath() !== $oldRewrite->getRequestPath()) {
return $this->redirect($request, $rewrite->getRequestPath(), OptionProvider::TEMPORARY);
}
}
}
//Below i have replaced static prefix
$replaceUrl = str_replace("your-static-prefix/", "", $request->getPathInfo());
$rewrite = $this->getRewrite($replaceUrl, $this->storeManager->getStore()->getId());
//$rewrite = $this->getRewrite($request->getPathInfo(), $this->storeManager->getStore()->getId());
// CODE FOR CATEGORY REWRITE
if ($rewrite === null)
{
$pathInfo = $request->getPathInfo();
$pathInfoArray = explode("/", $pathInfo);
$key = "";
if(!empty(trim($pathInfoArray[count($pathInfoArray) - 1])))
$key = trim($pathInfoArray[count($pathInfoArray) - 1]);
elseif(!empty(trim($pathInfoArray[count($pathInfoArray) - 2])))
$key = trim($pathInfoArray[count($pathInfoArray) - 2]);
if($key != "")
{
$objectManaer = MagentoFrameworkAppObjectManager::getInstance();
$category = $objectManaer->create('MagentoCatalogModelCategory');
$collection = $category->getCollection()->addAttributeToFilter('url_key', ['like' => '%' . $key . '%']);
if($collection->count())
{
$category = $collection->getFirstItem();
$path = $category->getPath();
$pathArray = explode("/", $category->getPath());
foreach(['1', '2', $category->getId()] as $del_val)
{
if (($categoryId = array_search($del_val, $pathArray)) !== false) {
unset($pathArray[$categoryId]);
}
}
$keyArray = ;
if(count($pathArray))
{
foreach($pathArray as $pathId)
{
$pathCategory = $objectManaer->create('MagentoCatalogModelCategory')->load($pathId);
$keyArray = $pathCategory->getUrlKey();
}
}
$keyArray = $category->getUrlKey();
$key = implode("/", $keyArray);
$key = '/' . $key;
$rewrite = $this->getRewrite($key, $this->storeManager->getStore()->getId());
}
}
}
if ($rewrite === null) {
return null;
}
if ($rewrite->getRedirectType()) {
return $this->processRedirect($request, $rewrite);
}
$request->setAlias(MagentoFrameworkUrlInterface::REWRITE_REQUEST_PATH_ALIAS, $rewrite->getRequestPath());
$request->setPathInfo('/' . $rewrite->getTargetPath());
return $this->actionFactory->create('MagentoFrameworkAppActionForward');
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param UrlRewrite $rewrite
* @return MagentoFrameworkAppActionInterface|null
*/
protected function processRedirect($request, $rewrite)
{
$target = $rewrite->getTargetPath();
if ($rewrite->getEntityType() !== Rewrite::ENTITY_TYPE_CUSTOM
|| ($prefix = substr($target, 0, 6)) !== 'http:/' && $prefix !== 'https:'
) {
$target = $this->url->getUrl('', ['_direct' => $target]);
}
return $this->redirect($request, $target, $rewrite->getRedirectType());
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param string $url
* @param int $code
* @return MagentoFrameworkAppActionInterface
*/
protected function redirect($request, $url, $code)
{
$this->response->setRedirect($url, $code);
$request->setDispatched(true);
return $this->actionFactory->create('MagentoFrameworkAppActionRedirect');
}
/**
* @param string $requestPath
* @param int $storeId
* @return UrlRewrite|null
*/
protected function getRewrite($requestPath, $storeId)
{
return $this->urlFinder->findOneByData([
UrlRewrite::REQUEST_PATH => trim($requestPath, '/'),
UrlRewrite::STORE_ID => $storeId,
]);
}
}
Reference: Magento 2 .2 - How to add Static Product Prefix to Product Url?
Thanks for your quick response, I did the same way but its not working for me. Please suggest
– Anurag Rana
6 hours ago
Did you ran full deployment script after doing this?
– Shoaib Munir
6 hours ago
Yes I did both upgrade and deploy.
– Anurag Rana
6 hours ago
In my case I don't need category path in the product URL for the same I have disabled from backend and its working fine. Now I need to add custom prefix in the same URl like example.com/custom-prefix/product.html which I tried with your solution but its not working for me not sure If I missed anything.
– Anurag Rana
6 hours ago
add a comment |
To add something like:
www.example.com/product-prefix/product1.html
You need to override two files in my custom module, One is Product Url Model and Another one is Router ControllerRouter
in di.xml
<preference for="MagentoCatalogModelProductUrl" type="VendorModuleNameModelUrl" />
<preference for="MagentoUrlRewriteControllerRouter" type="VendorModuleNameControllerRouter" />
in Url.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Product Url model
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace VendorModuleNameModel;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
class Url extends MagentoCatalogModelProductUrl
{
/**
* URL instance
*
* @var MagentoFrameworkUrlFactory
*/
protected $urlFactory;
/**
* @var MagentoFrameworkFilterFilterManager
*/
protected $filter;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkSessionSidResolverInterface
*/
protected $sidResolver;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkUrlFactory $urlFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilterFilterManager $filter
* @param MagentoFrameworkSessionSidResolverInterface $sidResolver
* @param UrlFinderInterface $urlFinder
* @param array $data
*/
public function __construct(
MagentoFrameworkUrlFactory $urlFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilterFilterManager $filter,
MagentoFrameworkSessionSidResolverInterface $sidResolver,
UrlFinderInterface $urlFinder,
array $data =
) {
parent::__construct($urlFactory, $storeManager, $filter, $sidResolver, $urlFinder, $data);
$this->urlFactory = $urlFactory;
$this->storeManager = $storeManager;
$this->filter = $filter;
$this->sidResolver = $sidResolver;
$this->urlFinder = $urlFinder;
}
/**
* Retrieve URL Instance
*
* @return MagentoFrameworkUrlInterface
*/
private function getUrlInstance()
{
return $this->urlFactory->create();
}
/**
* Retrieve URL in current store
*
* @param MagentoCatalogModelProduct $product
* @param array $params the URL route params
* @return string
*/
public function getUrlInStore(MagentoCatalogModelProduct $product, $params = )
{
$params['_scope_to_url'] = true;
return $this->getUrl($product, $params);
}
/**
* Retrieve Product URL
*
* @param MagentoCatalogModelProduct $product
* @param bool $useSid forced SID mode
* @return string
*/
public function getProductUrl($product, $useSid = null)
{
if ($useSid === null) {
$useSid = $this->sidResolver->getUseSessionInUrl();
}
$params = ;
if (!$useSid) {
$params['_nosid'] = true;
}
return $this->getUrl($product, $params);
}
/**
* Format Key for URL
*
* @param string $str
* @return string
*/
public function formatUrlKey($str)
{
return $this->filter->translitUrl($str);
}
/**
* Retrieve Product URL using UrlDataObject
*
* @param MagentoCatalogModelProduct $product
* @param array $params
* @return string
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getUrl(MagentoCatalogModelProduct $product, $params = )
{
$routePath = '';
$routeParams = $params;
$storeId = $product->getStoreId();
$categoryId = null;
if (!isset($params['_ignore_category']) && $product->getCategoryId() && !$product->getDoNotUseCategoryId()) {
$categoryId = $product->getCategoryId();
}
if ($product->hasUrlDataObject()) {
$requestPath = $product->getUrlDataObject()->getUrlRewrite();
$routeParams['_scope'] = $product->getUrlDataObject()->getStoreId();
} else {
$requestPath = $product->getRequestPath();
if (empty($requestPath) && $requestPath !== false) {
$filterData = [
UrlRewrite::ENTITY_ID => $product->getId(),
UrlRewrite::ENTITY_TYPE => MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::STORE_ID => $storeId,
];
if ($categoryId) {
$filterData[UrlRewrite::METADATA]['category_id'] = $categoryId;
}
$rewrite = $this->urlFinder->findOneByData($filterData);
if ($rewrite) {
$requestPath = $rewrite->getRequestPath();
$product->setRequestPath($requestPath);
} else {
$product->setRequestPath(false);
}
}
}
if (isset($routeParams['_scope'])) {
$storeId = $this->storeManager->getStore($routeParams['_scope'])->getId();
}
if ($storeId != $this->storeManager->getStore()->getId()) {
$routeParams['_scope_to_url'] = true;
}
if (!empty($requestPath)) {
$routeParams['_direct'] = $requestPath;
} else {
$routePath = 'catalog/product/view';
$routeParams['id'] = $product->getId();
$routeParams['s'] = $product->getUrlKey();
if ($categoryId) {
$routeParams['category'] = $categoryId;
}
}
// reset cached URL instance GET query params
if (!isset($routeParams['_query'])) {
$routeParams['_query'] = ;
}
$baseUrl = $this->storeManager->getStore()->getBaseUrl();
$productUrl = $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
$remainingUrl = str_replace($baseUrl, '', $productUrl);
$productUrl = $baseUrl."your-static-prefix/" . $remainingUrl;
//return $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
return $productUrl;
}
}
in Controller Router.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameController;
use MagentoUrlRewriteControllerAdminhtmlUrlRewrite;
use MagentoUrlRewriteModelOptionProvider;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
/**
* UrlRewrite Controller Router
*/
class Router implements MagentoFrameworkAppRouterInterface
{
/** var MagentoFrameworkAppActionFactory */
protected $actionFactory;
/** @var MagentoFrameworkUrlInterface */
protected $url;
/** @var MagentoStoreModelStoreManagerInterface */
protected $storeManager;
/** @var MagentoFrameworkAppResponseInterface */
protected $response;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkAppActionFactory $actionFactory
* @param MagentoFrameworkUrlInterface $url
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkAppResponseInterface $response
* @param UrlFinderInterface $urlFinder
*/
public function __construct(
MagentoFrameworkAppActionFactory $actionFactory,
MagentoFrameworkUrlInterface $url,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkAppResponseInterface $response,
UrlFinderInterface $urlFinder
) {
$this->actionFactory = $actionFactory;
$this->url = $url;
$this->storeManager = $storeManager;
$this->response = $response;
$this->urlFinder = $urlFinder;
}
/**
* Match corresponding URL Rewrite and modify request
*
* @param MagentoFrameworkAppRequestInterface $request
* @return MagentoFrameworkAppActionInterface|null
*/
public function match(MagentoFrameworkAppRequestInterface $request)
{
if ($fromStore = $request->getParam('___from_store')) {
$oldStoreId = $this->storeManager->getStore($fromStore)->getId();
$oldRewrite = $this->getRewrite($request->getPathInfo(), $oldStoreId);
if ($oldRewrite) {
$rewrite = $this->urlFinder->findOneByData(
[
UrlRewrite::ENTITY_TYPE => $oldRewrite->getEntityType(),
UrlRewrite::ENTITY_ID => $oldRewrite->getEntityId(),
UrlRewrite::STORE_ID => $this->storeManager->getStore()->getId(),
UrlRewrite::IS_AUTOGENERATED => 1,
]
);
if ($rewrite && $rewrite->getRequestPath() !== $oldRewrite->getRequestPath()) {
return $this->redirect($request, $rewrite->getRequestPath(), OptionProvider::TEMPORARY);
}
}
}
//Below i have replaced static prefix
$replaceUrl = str_replace("your-static-prefix/", "", $request->getPathInfo());
$rewrite = $this->getRewrite($replaceUrl, $this->storeManager->getStore()->getId());
//$rewrite = $this->getRewrite($request->getPathInfo(), $this->storeManager->getStore()->getId());
// CODE FOR CATEGORY REWRITE
if ($rewrite === null)
{
$pathInfo = $request->getPathInfo();
$pathInfoArray = explode("/", $pathInfo);
$key = "";
if(!empty(trim($pathInfoArray[count($pathInfoArray) - 1])))
$key = trim($pathInfoArray[count($pathInfoArray) - 1]);
elseif(!empty(trim($pathInfoArray[count($pathInfoArray) - 2])))
$key = trim($pathInfoArray[count($pathInfoArray) - 2]);
if($key != "")
{
$objectManaer = MagentoFrameworkAppObjectManager::getInstance();
$category = $objectManaer->create('MagentoCatalogModelCategory');
$collection = $category->getCollection()->addAttributeToFilter('url_key', ['like' => '%' . $key . '%']);
if($collection->count())
{
$category = $collection->getFirstItem();
$path = $category->getPath();
$pathArray = explode("/", $category->getPath());
foreach(['1', '2', $category->getId()] as $del_val)
{
if (($categoryId = array_search($del_val, $pathArray)) !== false) {
unset($pathArray[$categoryId]);
}
}
$keyArray = ;
if(count($pathArray))
{
foreach($pathArray as $pathId)
{
$pathCategory = $objectManaer->create('MagentoCatalogModelCategory')->load($pathId);
$keyArray = $pathCategory->getUrlKey();
}
}
$keyArray = $category->getUrlKey();
$key = implode("/", $keyArray);
$key = '/' . $key;
$rewrite = $this->getRewrite($key, $this->storeManager->getStore()->getId());
}
}
}
if ($rewrite === null) {
return null;
}
if ($rewrite->getRedirectType()) {
return $this->processRedirect($request, $rewrite);
}
$request->setAlias(MagentoFrameworkUrlInterface::REWRITE_REQUEST_PATH_ALIAS, $rewrite->getRequestPath());
$request->setPathInfo('/' . $rewrite->getTargetPath());
return $this->actionFactory->create('MagentoFrameworkAppActionForward');
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param UrlRewrite $rewrite
* @return MagentoFrameworkAppActionInterface|null
*/
protected function processRedirect($request, $rewrite)
{
$target = $rewrite->getTargetPath();
if ($rewrite->getEntityType() !== Rewrite::ENTITY_TYPE_CUSTOM
|| ($prefix = substr($target, 0, 6)) !== 'http:/' && $prefix !== 'https:'
) {
$target = $this->url->getUrl('', ['_direct' => $target]);
}
return $this->redirect($request, $target, $rewrite->getRedirectType());
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param string $url
* @param int $code
* @return MagentoFrameworkAppActionInterface
*/
protected function redirect($request, $url, $code)
{
$this->response->setRedirect($url, $code);
$request->setDispatched(true);
return $this->actionFactory->create('MagentoFrameworkAppActionRedirect');
}
/**
* @param string $requestPath
* @param int $storeId
* @return UrlRewrite|null
*/
protected function getRewrite($requestPath, $storeId)
{
return $this->urlFinder->findOneByData([
UrlRewrite::REQUEST_PATH => trim($requestPath, '/'),
UrlRewrite::STORE_ID => $storeId,
]);
}
}
Reference: Magento 2 .2 - How to add Static Product Prefix to Product Url?
To add something like:
www.example.com/product-prefix/product1.html
You need to override two files in my custom module, One is Product Url Model and Another one is Router ControllerRouter
in di.xml
<preference for="MagentoCatalogModelProductUrl" type="VendorModuleNameModelUrl" />
<preference for="MagentoUrlRewriteControllerRouter" type="VendorModuleNameControllerRouter" />
in Url.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Product Url model
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace VendorModuleNameModel;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
class Url extends MagentoCatalogModelProductUrl
{
/**
* URL instance
*
* @var MagentoFrameworkUrlFactory
*/
protected $urlFactory;
/**
* @var MagentoFrameworkFilterFilterManager
*/
protected $filter;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkSessionSidResolverInterface
*/
protected $sidResolver;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkUrlFactory $urlFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilterFilterManager $filter
* @param MagentoFrameworkSessionSidResolverInterface $sidResolver
* @param UrlFinderInterface $urlFinder
* @param array $data
*/
public function __construct(
MagentoFrameworkUrlFactory $urlFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilterFilterManager $filter,
MagentoFrameworkSessionSidResolverInterface $sidResolver,
UrlFinderInterface $urlFinder,
array $data =
) {
parent::__construct($urlFactory, $storeManager, $filter, $sidResolver, $urlFinder, $data);
$this->urlFactory = $urlFactory;
$this->storeManager = $storeManager;
$this->filter = $filter;
$this->sidResolver = $sidResolver;
$this->urlFinder = $urlFinder;
}
/**
* Retrieve URL Instance
*
* @return MagentoFrameworkUrlInterface
*/
private function getUrlInstance()
{
return $this->urlFactory->create();
}
/**
* Retrieve URL in current store
*
* @param MagentoCatalogModelProduct $product
* @param array $params the URL route params
* @return string
*/
public function getUrlInStore(MagentoCatalogModelProduct $product, $params = )
{
$params['_scope_to_url'] = true;
return $this->getUrl($product, $params);
}
/**
* Retrieve Product URL
*
* @param MagentoCatalogModelProduct $product
* @param bool $useSid forced SID mode
* @return string
*/
public function getProductUrl($product, $useSid = null)
{
if ($useSid === null) {
$useSid = $this->sidResolver->getUseSessionInUrl();
}
$params = ;
if (!$useSid) {
$params['_nosid'] = true;
}
return $this->getUrl($product, $params);
}
/**
* Format Key for URL
*
* @param string $str
* @return string
*/
public function formatUrlKey($str)
{
return $this->filter->translitUrl($str);
}
/**
* Retrieve Product URL using UrlDataObject
*
* @param MagentoCatalogModelProduct $product
* @param array $params
* @return string
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getUrl(MagentoCatalogModelProduct $product, $params = )
{
$routePath = '';
$routeParams = $params;
$storeId = $product->getStoreId();
$categoryId = null;
if (!isset($params['_ignore_category']) && $product->getCategoryId() && !$product->getDoNotUseCategoryId()) {
$categoryId = $product->getCategoryId();
}
if ($product->hasUrlDataObject()) {
$requestPath = $product->getUrlDataObject()->getUrlRewrite();
$routeParams['_scope'] = $product->getUrlDataObject()->getStoreId();
} else {
$requestPath = $product->getRequestPath();
if (empty($requestPath) && $requestPath !== false) {
$filterData = [
UrlRewrite::ENTITY_ID => $product->getId(),
UrlRewrite::ENTITY_TYPE => MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::STORE_ID => $storeId,
];
if ($categoryId) {
$filterData[UrlRewrite::METADATA]['category_id'] = $categoryId;
}
$rewrite = $this->urlFinder->findOneByData($filterData);
if ($rewrite) {
$requestPath = $rewrite->getRequestPath();
$product->setRequestPath($requestPath);
} else {
$product->setRequestPath(false);
}
}
}
if (isset($routeParams['_scope'])) {
$storeId = $this->storeManager->getStore($routeParams['_scope'])->getId();
}
if ($storeId != $this->storeManager->getStore()->getId()) {
$routeParams['_scope_to_url'] = true;
}
if (!empty($requestPath)) {
$routeParams['_direct'] = $requestPath;
} else {
$routePath = 'catalog/product/view';
$routeParams['id'] = $product->getId();
$routeParams['s'] = $product->getUrlKey();
if ($categoryId) {
$routeParams['category'] = $categoryId;
}
}
// reset cached URL instance GET query params
if (!isset($routeParams['_query'])) {
$routeParams['_query'] = ;
}
$baseUrl = $this->storeManager->getStore()->getBaseUrl();
$productUrl = $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
$remainingUrl = str_replace($baseUrl, '', $productUrl);
$productUrl = $baseUrl."your-static-prefix/" . $remainingUrl;
//return $this->getUrlInstance()->setScope($storeId)->getUrl($routePath, $routeParams);
return $productUrl;
}
}
in Controller Router.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameController;
use MagentoUrlRewriteControllerAdminhtmlUrlRewrite;
use MagentoUrlRewriteModelOptionProvider;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;
/**
* UrlRewrite Controller Router
*/
class Router implements MagentoFrameworkAppRouterInterface
{
/** var MagentoFrameworkAppActionFactory */
protected $actionFactory;
/** @var MagentoFrameworkUrlInterface */
protected $url;
/** @var MagentoStoreModelStoreManagerInterface */
protected $storeManager;
/** @var MagentoFrameworkAppResponseInterface */
protected $response;
/** @var UrlFinderInterface */
protected $urlFinder;
/**
* @param MagentoFrameworkAppActionFactory $actionFactory
* @param MagentoFrameworkUrlInterface $url
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkAppResponseInterface $response
* @param UrlFinderInterface $urlFinder
*/
public function __construct(
MagentoFrameworkAppActionFactory $actionFactory,
MagentoFrameworkUrlInterface $url,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkAppResponseInterface $response,
UrlFinderInterface $urlFinder
) {
$this->actionFactory = $actionFactory;
$this->url = $url;
$this->storeManager = $storeManager;
$this->response = $response;
$this->urlFinder = $urlFinder;
}
/**
* Match corresponding URL Rewrite and modify request
*
* @param MagentoFrameworkAppRequestInterface $request
* @return MagentoFrameworkAppActionInterface|null
*/
public function match(MagentoFrameworkAppRequestInterface $request)
{
if ($fromStore = $request->getParam('___from_store')) {
$oldStoreId = $this->storeManager->getStore($fromStore)->getId();
$oldRewrite = $this->getRewrite($request->getPathInfo(), $oldStoreId);
if ($oldRewrite) {
$rewrite = $this->urlFinder->findOneByData(
[
UrlRewrite::ENTITY_TYPE => $oldRewrite->getEntityType(),
UrlRewrite::ENTITY_ID => $oldRewrite->getEntityId(),
UrlRewrite::STORE_ID => $this->storeManager->getStore()->getId(),
UrlRewrite::IS_AUTOGENERATED => 1,
]
);
if ($rewrite && $rewrite->getRequestPath() !== $oldRewrite->getRequestPath()) {
return $this->redirect($request, $rewrite->getRequestPath(), OptionProvider::TEMPORARY);
}
}
}
//Below i have replaced static prefix
$replaceUrl = str_replace("your-static-prefix/", "", $request->getPathInfo());
$rewrite = $this->getRewrite($replaceUrl, $this->storeManager->getStore()->getId());
//$rewrite = $this->getRewrite($request->getPathInfo(), $this->storeManager->getStore()->getId());
// CODE FOR CATEGORY REWRITE
if ($rewrite === null)
{
$pathInfo = $request->getPathInfo();
$pathInfoArray = explode("/", $pathInfo);
$key = "";
if(!empty(trim($pathInfoArray[count($pathInfoArray) - 1])))
$key = trim($pathInfoArray[count($pathInfoArray) - 1]);
elseif(!empty(trim($pathInfoArray[count($pathInfoArray) - 2])))
$key = trim($pathInfoArray[count($pathInfoArray) - 2]);
if($key != "")
{
$objectManaer = MagentoFrameworkAppObjectManager::getInstance();
$category = $objectManaer->create('MagentoCatalogModelCategory');
$collection = $category->getCollection()->addAttributeToFilter('url_key', ['like' => '%' . $key . '%']);
if($collection->count())
{
$category = $collection->getFirstItem();
$path = $category->getPath();
$pathArray = explode("/", $category->getPath());
foreach(['1', '2', $category->getId()] as $del_val)
{
if (($categoryId = array_search($del_val, $pathArray)) !== false) {
unset($pathArray[$categoryId]);
}
}
$keyArray = ;
if(count($pathArray))
{
foreach($pathArray as $pathId)
{
$pathCategory = $objectManaer->create('MagentoCatalogModelCategory')->load($pathId);
$keyArray = $pathCategory->getUrlKey();
}
}
$keyArray = $category->getUrlKey();
$key = implode("/", $keyArray);
$key = '/' . $key;
$rewrite = $this->getRewrite($key, $this->storeManager->getStore()->getId());
}
}
}
if ($rewrite === null) {
return null;
}
if ($rewrite->getRedirectType()) {
return $this->processRedirect($request, $rewrite);
}
$request->setAlias(MagentoFrameworkUrlInterface::REWRITE_REQUEST_PATH_ALIAS, $rewrite->getRequestPath());
$request->setPathInfo('/' . $rewrite->getTargetPath());
return $this->actionFactory->create('MagentoFrameworkAppActionForward');
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param UrlRewrite $rewrite
* @return MagentoFrameworkAppActionInterface|null
*/
protected function processRedirect($request, $rewrite)
{
$target = $rewrite->getTargetPath();
if ($rewrite->getEntityType() !== Rewrite::ENTITY_TYPE_CUSTOM
|| ($prefix = substr($target, 0, 6)) !== 'http:/' && $prefix !== 'https:'
) {
$target = $this->url->getUrl('', ['_direct' => $target]);
}
return $this->redirect($request, $target, $rewrite->getRedirectType());
}
/**
* @param MagentoFrameworkAppRequestInterface $request
* @param string $url
* @param int $code
* @return MagentoFrameworkAppActionInterface
*/
protected function redirect($request, $url, $code)
{
$this->response->setRedirect($url, $code);
$request->setDispatched(true);
return $this->actionFactory->create('MagentoFrameworkAppActionRedirect');
}
/**
* @param string $requestPath
* @param int $storeId
* @return UrlRewrite|null
*/
protected function getRewrite($requestPath, $storeId)
{
return $this->urlFinder->findOneByData([
UrlRewrite::REQUEST_PATH => trim($requestPath, '/'),
UrlRewrite::STORE_ID => $storeId,
]);
}
}
Reference: Magento 2 .2 - How to add Static Product Prefix to Product Url?
answered 6 hours ago
Shoaib MunirShoaib Munir
363114
363114
Thanks for your quick response, I did the same way but its not working for me. Please suggest
– Anurag Rana
6 hours ago
Did you ran full deployment script after doing this?
– Shoaib Munir
6 hours ago
Yes I did both upgrade and deploy.
– Anurag Rana
6 hours ago
In my case I don't need category path in the product URL for the same I have disabled from backend and its working fine. Now I need to add custom prefix in the same URl like example.com/custom-prefix/product.html which I tried with your solution but its not working for me not sure If I missed anything.
– Anurag Rana
6 hours ago
add a comment |
Thanks for your quick response, I did the same way but its not working for me. Please suggest
– Anurag Rana
6 hours ago
Did you ran full deployment script after doing this?
– Shoaib Munir
6 hours ago
Yes I did both upgrade and deploy.
– Anurag Rana
6 hours ago
In my case I don't need category path in the product URL for the same I have disabled from backend and its working fine. Now I need to add custom prefix in the same URl like example.com/custom-prefix/product.html which I tried with your solution but its not working for me not sure If I missed anything.
– Anurag Rana
6 hours ago
Thanks for your quick response, I did the same way but its not working for me. Please suggest
– Anurag Rana
6 hours ago
Thanks for your quick response, I did the same way but its not working for me. Please suggest
– Anurag Rana
6 hours ago
Did you ran full deployment script after doing this?
– Shoaib Munir
6 hours ago
Did you ran full deployment script after doing this?
– Shoaib Munir
6 hours ago
Yes I did both upgrade and deploy.
– Anurag Rana
6 hours ago
Yes I did both upgrade and deploy.
– Anurag Rana
6 hours ago
In my case I don't need category path in the product URL for the same I have disabled from backend and its working fine. Now I need to add custom prefix in the same URl like example.com/custom-prefix/product.html which I tried with your solution but its not working for me not sure If I missed anything.
– Anurag Rana
6 hours ago
In my case I don't need category path in the product URL for the same I have disabled from backend and its working fine. Now I need to add custom prefix in the same URl like example.com/custom-prefix/product.html which I tried with your solution but its not working for me not sure If I missed anything.
– Anurag Rana
6 hours ago
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f260746%2fmagento-2-2-6-how-we-can-add-custom-prefix-in-product-url%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown