Retrieving Subcategory or Product URLs in Magento for Hreflang Implementation
Are you facing challenges while trying to extract the subcategory or product URL after the main domain name in your Magento store? You’re not alone! Many online retailers struggle with this when implementing hreflang tags for multilingual and multi-currency sites.
Understanding the Challenge
The core issue lies in retrieving only the desired portion of the URL, specifically the part that comes after your base domain. For instance, if your URL is https://domain.com/shoes.html, you want to extract just shoes.html.
This becomes crucial when working with multiple stores (e.g., .nl and .be) and needing to link between them using hreflang for SEO purposes.
The Wrong Approach
Many developers initially try using the built-in Magento helper:
{{helper('core/url')->getCurrentUrl()}}
However, this returns the entire URL, not just the desired portion. As a result, you get https://domain.com/shoes.html, which isn’t what we need.
The Correct Method: Extracting the Desired URL
To achieve your goal, you’ll need to manipulate the URL string provided by Magento. Here’s how you can do it:
- First, retrieve the full URL using the helper:
<?php $fullUrl = Mage::helper('core/url')->getCurrentUrl(); ?>
- Then, use PHP’s built-in
parse_urlfunction to break down the URL into its components:
<?php
$parsedUrl = parse_url($fullUrl);
$path = substr($parsedUrl['path'], 1); // Remove leading slash
?>
- Finally, output the desired subcategory or product name:
<span>{{ $path }}</span>
Example Output
Given your URL https://domain.com/shoes.html, this code will output: <span>shoes.html</span>
Why This Matters for Hreflang Implementation
With the extracted subcategory or product name, you can now easily implement hreflang tags across your multiple Magento stores.
For instance, in the <head> section of your page:
<link rel="alternate" href="https://domain.com/nl/shoes.html" hreflang="nl-nl" />
<link rel="alternate" href="https://domain.com/be/shoes.html" hreflang="fr-fr" />
This tells search engines that the shoes.html pages in both your .nl and .be stores are related, helping to improve visibility for your multilingual site.
Conclusion
Retrieving the subcategory or product name after the main domain is a common challenge but can be easily solved with some basic URL manipulation using PHP’s built-in functions within your Magento templates.
Remember, accurate hreflang implementation requires careful management of URLs across different languages and stores. Regular audits are essential to ensure the integrity of your structured data markup.
For more advanced SEO techniques compatible with modern e-commerce platforms like Magento 2, I recommend exploring our comprehensive guide on Advanced SEO Techniques for Magento.
In this guide, you’ll find in-depth tutorials and best practices for optimizing your Magento store’s performance and visibility.