简体   繁体   中英

How do I create permanent redirects for old url keys with code?

Problem

I have added a new catergory that has the urlkey of " shoes ". This urlkey was found to be problematic as the URL redirect linked it to shoes-86 . This was because there are several dozen disabled/legacy products with the same url key (shoes). Understanding that manually creating redirects would have adverse side effects. I was tasked to solve it programmatically using scripts and change all the urlkeys of the products so that magento can fix the redirects itself. This has created some problems.

Attempted solution

Currently i have this code which doesn't work, it does not create redirects. The following code is suppose to retrieve products with the url key of black_canvas_sneakers. It does this because it is my test product and I want to see the effects before applying the script to the whole database. This script only seems to retrieve products from the default store, no other stores for some odd reason. The problem i'm looking for the solution for is, why doesn't this code work and what can i do to make it work?

<?php

require 'app/Mage.php';
umask(0);
Mage::app()->setCurrentStore('0');



$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('url_key', 'black-canvas-sneakers');

foreach ($collection as $product) {
    $product->setData('save_rewrites_history', true)->save();

    break;
}

I know the following code can make a redirect but senior magento developers have told me it could lead to unexpected side-effects. Thus this code is not best practice for creating permanent redirects.

/*Mage::getModel('core/url_rewrite')
            ->setIsSystem(0)
            ->setStoreId(2)
            ->setOptions('RP')
            ->setIdPath($product->getUrlKey() . '.html')
            ->setTargetPath($product->getUrlKey() . '.html')
            ->setRequestPath('shoes-' . $product->getId() . '.html' )
            ->save();*/

Manually altering url rewrite for default entities (like products and categories) might have adverse affects. The url indexer will recreate records that you may have deleted/changed.

You've described your solution, but not the problem you're trying to solve. Why are you creating redirects in the first place?

By default, when changing the url_key in the admin, there is an option to create a permanent redirect.

管理

The same is true when updating the url_key programmatically

Mage::getModel('catalog/product')->load(905)
    ->setUrlKey('new-url-124')
    ->save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM