For when you don't want to do them all manually

A Simple PHP Script for Adding hreflang

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.

<link rel=”alternate” href=”http://otherdomain.com.au<?php echo parse_url($_SERVER[‘REQUEST_URI’],PHP_URL_PATH); ?>” hreflang=”en-au” />

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

  1. Copy script
  2. Change domain to the alternate version
  3. Change the hreflang attribute to the specific country being targeted
  4. Add to the head of your template files
  5. Test
  6. 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:

Chris is Director of Organic Search for Reprise Melbourne.

2 thoughts on “A Simple PHP Script for Adding hreflang

  1. Matthew Shepherd Reply

    Bookmarking this for the next hreflang implementation that I tackle. I’ll let you know how it goes. Thanks for this Chris!

  2. Matthew Shepherd Reply

    Bookmarking this for the next hreflang implementation that I tackle. I’ll let you know how it goes. Thanks for this Chris!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>