views:

426

answers:

2

Hello -

Does anyone know how to modify the Wordpress canonical links to add a custom URL parameter?

I have a Wordpress site with a page that queries a separate (non-Wordpress) database. I passed the URL parameter "pubID" to display individual books and it is working OK.

Example: http://www.uglyducklingpresse.org/catalog/browse/item/?pubID=63

But the individual book pages are not showing up properly in Google - the ?pubID parameter is stripped out.

I think maybe this is because all the item pages have the same auto-generated "canonical" URL link tag in the source - one with the "pubID" parameter stripped out.

Example: link rel='canonical' href='http://www.uglyducklingpresse.org/catalog/browse/item/'

Is there a way to perhaps edit .htaccess to add a custom URL parameter to Wordpress, so that the parameter is not stripped out by permalinks and the "canonical" links?

Or maybe there's another solution ... Thank you for any ideas!

A: 

You should be able to replace Wordpress's rel_canonical action function with your own function in which (when your conditions are meet) you create a canonical link appending the query string variable. The following should work, although you'll probably need to change the conditions to meet your needs.

remove_action('wp_head', 'rel_canonical');
add_action('wp_head', 'my_rel_canonical');

function my_rel_canonical() {
    if (is_page('item') && isset($_GET['pubID'])) {
        global $post;
        $link = get_permalink($post->ID) . '?pubID=' . absint($_GET['pubID']);
        echo "<link rel='canonical' href='$link' />\n";
    } else {
        rel_canonical();
    }
}
Richard M
Wow thank you Richard! This code did exactly what I needed it to and the canonical links are fixed. Thank you for your help!!
kiko
A: 

I'm not actually a Word Press programmer, but I'd like to learn a bit more about how these canonical links are created. I'm in a "I'm just gonna create it all from scratch so I can learn more" mode I guess. Do either of you know much about how WP references them?

Is it that WP passes the URL and parses it into a string then searches the DB for a post that matches?

Sorry if this is neither the time or place for this question, and thanks for any insight you may provide

Daniel burke
Hi Daniel, I think the canonical links just print out the permalink URL, which is already available to Wordpress inside the loop. I think you could look in the wp-includes/canonical.php and wp-includes/link-template.php files to see the code.
kiko