A Customisable PHP Script That Lets You Target The Same File Path On Other Domains Using hreflang
The code in this script lets you specify the domains you’re using, then simply returns the file path at the end.
This is a simple, low overhead way of creating a hreflang tag for PHP sites. I specifically used this for WordPress, adding it in the header template.
To use this script, just add the following between the head tags of your template:
Disclaimer: You may need to check that you inputs are being sanitised. This is a basic method, and will need testing to make sure it works with your configuration.
Remember to replace “http://otherdomain.com.au” with your own domain and change the hreflang for the target country.
If you’re not sure how to use the hreflang tag, you can learn more about it here: http://www.w3schools.com/tags/att_a_hreflang.asp
I’ll break down the script here:
- href=”http://otherdomain.com.au = The standard link to your domain
- <?php echo parse_url($_SERVER[‘REQUEST_URI’],PHP_URL_PATH); ?> = Returns the filepath of the page being viewed
Steps for Adding hreflang Script
- Copy script
- Change domain to the alternate version
- Change the hreflang attribute to the specific country being targeted
- Add to the head of your template files
- Test
- Enjoy a cold beverage
Let me know in the comments if you have any problems with this, or if it works great.
You might also want to watch this video with the effervescent Maile Ohye:
Bookmarking this for the next hreflang implementation that I tackle. I’ll let you know how it goes. Thanks for this Chris!
Bookmarking this for the next hreflang implementation that I tackle. I’ll let you know how it goes. Thanks for this Chris!
Just a quick comment, in case anybody is attempting to set this up for WordPress.
The above worked for me, when placed in the head section.
Be sure to change apostrophes and quotes to standard unicode, because when copy/pasted from above they don’t work.
Chris