How to generate canonical URLs in WordPress without plugin

Canonical URL is very important for SEO. Here’s how to generate canonical URLs in WordPress without plugin.

If you do not want to read the details on how canonical URLs are generated in WordPress, here is our full code. Paste this code before closing </head> tag in your header.php.

For single posts, pages use this first code:

<?php if ( is_singular() ) { ?> <link rel="canonical" href="<?php the_permalink(); ?>" /> <?php } ?>

For archives such as: categories, tags or any other taxonomy use this second code:

<?php if ( is_archive() || is_home() || is_category() ) { ?> <link rel="canonical" href="https://www.yourdomain.com<?php echo $_SERVER['REQUEST_URI'];?>"> <?php } ?>

In fact there are two codes here. One for single posts and pages and one for archives. Someone with advanced PHP knowledge would be able to merge both codes into a single code.

Sources:

These codes are found on many sites on the internet, but we’ve used only two sources:

First code: <?php if ( is_singular() ) { ?><link rel=”canonical” href=”<?php the_permalink(); ?>” /> <?php } ?>  /Bin-blog

Second code (only one piece of code): <link rel=”canonical” href=”https://www.yourdomain.com<?php echo $_SERVER[‘REQUEST_URI’];?>”> /This is found in many web tutorials.

Both codes are written to be used throughout the website. But there are some things that don’t work.

The first code is pretty good, but there is a problem. In the posts list this code does not generate the archive link, but the first post link.

Even the second code is fine but it also has a problem that we unfortunately haven’t solved at all, at least not entirely. This code generates a canonical URL as it is entered in the address bar.

Example: If you enter www.domain.com/my-post/// in the adress bar, then the canonical URL is generated as it is written with multiple slashes.

That’s why we modified both codes and put two instead of one.

Clarification: This tutorial is written based on experiments with our themes and servers. If these codes do not work well for us, we cannot say that they do not work on other servers and that  who created them did not write codes correctly.

Contact us: info@indexofapps.com