8

Is there a way to get a list of products with their current canonical url on command line?

class Mage_Shell_UrlTest extends Mage_Shell_Abstract
{

public function run()
{
    $productCollection = Mage::getResourceModel('catalog/product_collection')
            ->addStoreFilter()
            ->addUrlRewrite()
            ->addAttributeToSelect('*')
            ->setPageSize(10) // just for testing
            ->addFieldToFilter('visibility',Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
            ->addAttributeToFilter('status', array(
                'eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED
            ));

    Mage::getSingleton('cataloginventory/stock')
            ->addInStockFilterToCollection($productCollection);

    foreach ($productCollection as $product) {

        $url = $product->getUrlModel()->getUrl($product, array('_ignore_category' => true));

        echo PHP_EOL . $url . PHP_EOL; // debug output
    }
}
}

$shell = new Mage_Shell_UrlTest();
$shell->run();

I run it with php -f magento/shell/urlTest.php and this gives me something like this:

http://www.domain.com/urlTest.php/catalog/product/view/_ignore_category/1/id/307/s/any_valid_product_url_key

Kevin
  • 1,232
  • 10
  • 28

2 Answers2

4

By default magento uses the same code to get the canonical url in Mage_Catalog_Block_Product_View::_prepareLayout() so the code should be fine. The only difference is for which store the code is executed.

It doesn't work in shell scripts because they are executed for the admin store (see Mage_Shell_Abstract::__construct() where Mage::app() is initialized). You could use Mage::app()->setCurrentStore('default'); where you need to replace default by your store and the right urls should be printed.

Simon H
  • 2,495
  • 4
  • 30
  • 38
-2

I maybe do not understand properly what you mean by "canonical url" but if you mean the url of the product with its ID and the key at the end that is normally the "canonical url" for magento as it is supposed to be unique at a moment, you should just take away the params of the getUrl. If you do not want the key, you can still use :

$url = substr($url, 0, strrpos('/s/')); 

I hope it helps, if not, please precise the result you want.

Christophe Ferreboeuf
  • 1,048
  • 14
  • 26
  • sorry, you should be familar with magento to answer this question. the canonical link is the unique uri to a product without any category-informations or something else. in addition magento has a table called core_rewrite_url to resolve renamed product url keys – Kevin Jul 02 '14 at 16:54
  • so, please read again my answer and you should get canonical url in the magento definition. – Christophe Ferreboeuf Jul 02 '14 at 19:30
  • 1
    Sorry, this answer is almost dangerous. Please see the accepted answer which is the proper way to do it. Actually I can't see how this can work as a hack anyway. – Christian Jul 02 '14 at 20:04