Question

I have two websites using WordPress: www.exemple.com (fr-FR) and ca.exemple.com/fr (fr-CA)

To avoid duplicate content on Google I have to change dynamically this meta:

<link rel="alternate" hreflang="fr-CA" href="ca.exemple.com/fr/shop">

So when I put in header.php on www.exemple.com/shop

<link rel="alternate" hreflang="fr-CA" href="<?php echo str_replace("//", "//ca.", get_site_url() . $_SERVER['REQUEST_URI']); ?>" />

It returns:

<link rel="alternate" hreflang="pl" href="ca.exemple.com/shop">

How can I add /fr/ between .com and /shop/?

EDIT : SOLUTION

I've made a special code that will verify if the code exist on the other page so we dont have 404 errors for nothing, here it is :

<?php
$alt_url = str_replace( "ca.exemple.com/fr/fr", "www.exemple.com" , get_site_url() . $_SERVER['REQUEST_URI']);
$currentz = str_replace( "ca.exemple.com/fr/fr" , "ca.exemple.com/fr" ,   get_site_url() . $_SERVER['REQUEST_URI']);
$file_headers = @get_headers($alt_url);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {

}
else {
echo "<link rel=\"alternate\" hreflang=\"fr-CA\" href=\"$currentz\" />";
echo "\n";
echo "<link rel=\"alternate\" hreflang=\"fr-FR\" href=\"$alt_url\" />";
}
?>
Was it helpful?

Solution

Just add in the string in your concatenation

<?php echo str_replace("//", 
          "//ca.", get_site_url() .'/fr'. $_SERVER['REQUEST_URI']); 

I probably wouldn't do it like this. But that's the quick answer.

There's no need to run str_replace over the whole string.

 echo str_replace('//'.'//ca.',get_site_url()).'/fr'/. $_SERVER['REQUEST_URI'];

Also, there are functions for parsing urls

OTHER TIPS

Try this one

$url = 'http://www.example.com/shop';

$path = parse_url($url, PHP_URL_PATH);


echo str_replace($path,'/fr'.$path, $url); // http://example.com/fr/shop

You could add another string replace after your existing string replace. For example:

 <?php
       $url = str_replace("//", "//ca.", "http://www.yahoo.com/shop");
       $url = str_replace(".com", ".com/fr", $url);
       echo $url;
    ?>

Would result in:

http://ca.www.yahoo.com/fr/shop
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top