I need PHP code to generate a dynamic canonical URL within the <link /> tag as follows:
<link rel="canonical" href="php goes here" />
My site uses PHP to generate variables as follows:
http://www.mysite.com/script.php?var1=blue&var2=large&pointlessvar=narrow
I want to be able to return a canonical URL that removes the &pointlessvar=narrow
And re-arranges the variables in the manner as I see fit, like this:
<link rel="canonical" href="http://www.mysite.com/script.php?var2=large&var1=blue" />
I want to do this for SEO purposes as my site contains many variables in different orders that give different URL’S for essentially the same content (to prevent duplication in the SERPS and to concentrate the link juice)
Can anybody suggest some PHP code that I can place in the <link /> tag?
To make a canonical url, you should actually make sure, you got only the parameters you need and put them in a fixed order too. This code does that. It filters the list of _GET paramters and build a new url with only the desired ones. I put it some comments, so you can easily adjust this code to fit your needs.
I use array_filter, because I’m not sure what happens if you unset array elements within a foreach on the array.