I'm currently working on a website which provides content to users based on their region. As a result the website has subdirectories for the appropriate regions. For example, a pricing page would look something like this:
In order to target the appropriate search engines and signify to Google that there are different versions of the page, I've implemented hreflang
tags. A good example of a site that uses these would be view-source:https://www.tripadvisor.ie/
. If you view the source you will see a long list of hreflang
tags to denote multiple regional versions of the page.
So, for my site, I decided to write a PHP script that would output the relevant hreflang
tags on the correct page:
<?php $url = $_SERVER['REQUEST_URI']; ?>
<?php if(strpos($url, "pricing") == true): ?>
<link rel="alternate" href="http://www.mydomain.com/ie/pricing/" hreflang="en-ie" />
<link rel="alternate" href="http://www.mydomain.com/gb/pricing/" hreflang="en-gb" />
<link rel="alternate" href="http://www.mydomain.com/fr/pricing/" hreflang="en-fr" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="en" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="x-default" />
<?php endif; ?>
However, the problem I'm facing is that if the URL contains pricing
ANYWHERE it will output the above which is not correct if the URL was something like: http://www.mydomain.com/pricing-types
.
To counteract this I added another if
statement which checks to ensure that the word types
is not present in the URL:
<?php $url = $_SERVER['REQUEST_URI']; ?>
<?php if(strpos($url,"pricing") == true && strpos($url, "types") == false): ?>
<link rel="alternate" href="http://www.mydomain.com/ie/pricing/" hreflang="en-ie" />
<link rel="alternate" href="http://www.mydomain.com/gb/pricing/" hreflang="en-gb" />
<link rel="alternate" href="http://www.mydomain.com/fr/pricing/" hreflang="en-fr" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="en" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="x-default" />
<?php endif; ?>
Would anyone have any recommendations of how I could improve my script to read the URLs and match them to the appropriate hreflang
tags but being more explicit in the URLs I read?