Getting Formatted Product URLs in Magento
As a senior developer, I often encounter situations where clients need to extract formatted product URLs from a Magento collection. The challenge is that by default, Magento provides the URL with additional parameters and a different format than what we usually expect for SEO-friendly links.
Let me guide you through the process of getting the correct, clean product URL in Magento 2 or earlier versions.
The Problem: Default Magento Product URL Format
When you use the standard methods to get a product URL:
$productUrl = $product->getProductUrl();
Or
$categoryId = $product->getCategoryIds();
$url = $product->setCategoryId($categoryId)->getProductUrl();
You’ll end up with URLs like this:
https://www.myshop.co.uk/index.php/catalog/product/view/id/100/
Or
https://www.myshop.co.uk/index.php/catalog/product/view/id/100
Clearly, these aren’t the clean, SEO-friendly URLs we want.
The Solution: Using Magento’s Core Functions
To get the correct URL format, you should use Magento’s core functions that are designed to handle this:
$productUrl = $product->getProductUrl(false);
Or if you’re using a product collection:
foreach ($collection as $product) {
$productUrl = $product->getProductUrl(false);
}
The false parameter is the key here. It tells Magento not to include the store code in the URL, which gives us the clean URLs we want.
Example: Getting a Single Product URL
Let’s assume you have a product SKU:
$product = $objectManager->create('Magento\Catalog\Model\Product')->loadByAttribute('sku', 'red-bouncy-ball');
You can get its formatted URL like this:
$formattedUrl = $product->getProductUrl(false);
echo $formattedUrl; // Outputs: https://www.myshop.co.uk/red-bouncy-ball.html
Example: Getting URLs from a Collection
If you have a product collection, you can loop through it and get the formatted URLs:
$collection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
foreach ($collection as $product) {
$formattedUrl = $product->getProductUrl(false);
// Process or store $formattedUrl
}
Conclusion: Formatting Product URLs in Magento
In summary, to get the formatted product URL you want, always use getProductUrl(false), regardless of whether you’re working with a single product or a collection.
Remember, using Magento’s core functions ensures that your URLs are consistent and SEO-friendly. It also saves you from having to manually parse and format the URLs yourself.
For more advanced techniques and customizations related to URL management in Magento, I recommend checking out Laravel Company’s Magento development services. We specialize in helping businesses optimize their e-commerce platforms for better performance and SEO.