Setting custom canonical urls

I have a page that requests and displays information from a database. All is fine but I'm having some trouble setting custom canonical URLs for this single page only and its URLs (with parameters inside).

Example:

https://example.com/primary-page

https://example.com/primary-page?requested_id=1

https://example.com/primary-page?requested_id=2

https://example.com/primary-page?requested_id=3 and so on...

These links with "?requested_id=id" automatically inherit the same canonical link as the "primary-page". Which I would like to modify in order for these links to have their own and full URLs as canonical link.

I've been looking for a solution for a few days now without luck. I hope one of you will be able to help me, which I do not doubt at all.

So, thank you so much in advance!

Topic rel-canonical functions php customization Wordpress

Category Web


It depends on how your canonical URLs are being written to the page. In your theme's header you may find something like:

<link rel="canonical" href="<?php echo get_permalink(); ?>">

If you are able to edit your theme (or child theme if using a distributed theme) you can put whatever you want there instead. For instance, you could put:

<link rel="canonical" href="<?php echo $_SERVER['REQUEST_URI']; ?>">

$_SERVER['REQUEST_URI'] includes all of the query parameters.

(Or if you are using a plugin like Yoast, it will add the canonical link to your page for you. You should be able to filter this output. With Yoast, it is the "wpseo_canonical" filter.)

But remember, in many cases it makes sense to not include the query parameters, for instance two pages that vary only in a ?sortby= parameter do in fact share duplicate content, and the whole point of canonical tags is to help identify duplicate content.

It might make more sense to add your parameter as a query arg and give it a rewrite rule, so that it becomes part of the more standard URL and is included by default. Instead of primary-page?requested_id=1 it could be primary-page/1. It also looks a little better.

If you want to do that, there are a couple of different answers on this related question.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.