0

At the moment, I have a controller that returns the url for one product, based on a pre-defined custom attribute. I'm able to get the product I want, but the url that I get from the object, takes me to a 404. I've tried many different methods based on other similar questions, without success:

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('upc');  
$storeId = Mage::app()->getStore()->getStoreId();
$collection->addFieldToFilter(array(
    array('attribute'=>'upc','eq'=> $barcode),
)); 
$url = null;
foreach ($collection as $product) {
    $url = $product->getProductUrl();
    break;
}
Mage::log($url);

On the code above, I'm able to find my product without problems. Calling getProductUrl also returns a URL. If I browse to the URL though, I get a 404 Magento page. I've also tried adding something like this, before looping through the collection:

$collection->addUrlRewrite($categoryId);

If I try to get the URL by using the id, like below, I get a different URL, but invalid as well:

$url = Mage::getModel('catalog/product')->setStoreId($storeId)->load($id)->getProductUrl();

None of the urls that I get, exist in the URL rewrite list in the Admin Panel. As a side note, I've flushed my cache and reindexed everything prior to each method above. Would appreciate if anyone could enlighten me as to what's going on!

  • What version of Magento? – Tyler V. May 9 '15 at 1:34
1

you have set setstoreid whenever you fetch url from product collection

So now for loop becomes like

$url = null;
foreach ($collection as $product) {

    $product->setStoreId($storeId);

    $url = $product->getProductUrl();
    break;
}
Mage::log($url);

this one is working for me.

Note: your URL index should be up to date. and if you are using default magento's SEO functionality like include or exclude category from product url just look carefully in this case.

hope this helps you.

0

Look in core_url_rewrite for clues. You can also go to a product view directly with the url catalog/product/view/id/[PRODUCT_ID].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.