Magento – Resolving Invalid URLs from Mage::getUrl with _use_rewrite

catalogsearchoverrides

I need to print a URL on a template that leads to the search page with the search query parameter already predefined.

This is the code I have at the moment:

$url = Mage::getUrl('catalogsearch/advanced/result', array('_use_rewrite' => true, '_query' => $query));

Where $queryis an array containing the search, e.g. $query['flavor'] = "bacon" to search using attributes.

If I understand correctly, _use_rewrite should check if there is any URL rewrite already in place, and return that URL instead. I will use URL rewriting later on, but at the moment there is not any rewrite defined, so I assume it should return just the regular URL.

Somehow, the getUrl function doesn't return the search URL correctly when _use_rewrite_ is set to true, and it instead returns the base store URL without the catalogsearch module on the URL. I.e.:

http://mystore.local/?flavor=bacon

But if _use_rewrite is set to false, it prints the URL correctly:

http://mystore.local/catalogsearch/result/?flavor=bacon

Is everything working as expected?

Best Answer

It seems that the '_use_rewrite' flag only works for rewrite rules added to the Magento backend (admin section).

Here is a function that should do what you need:

$rewrite = Mage::getModel('core/url_rewrite');
        if (Mage::app()->getStore()->getId()) {
            $rewrite->setStoreId(Mage::app()->getStore()->getId());
        }

        $idPath = 'mymodule';

        // Look for a rewrite rule with this id
        $rewrite->loadByIdPath($idPath);

        // If found return our URL rewrite
        if ($rewrite->getId()) {
            return Mage::getUrl($rewrite->getRequestPath());
        }

        // Else return standard URL
        return $idPath;

Here is a link that has some more info on this.