Skip to content

Instantly share code, notes, and snippets.

@GwynethLlewelyn
Last active May 27, 2021 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GwynethLlewelyn/82ace1c8bf0e8669b540c6274138f653 to your computer and use it in GitHub Desktop.
Save GwynethLlewelyn/82ace1c8bf0e8669b540c6274138f653 to your computer and use it in GitHub Desktop.
Minimalistic code to add rel=canonical links on HTML header
<?php
/**
* Minimalistic code to add rel=canonical links on HTML header.
*
* No wish to install a full-blown SEO plugin just to get those rel=canonical links? That's fine!
* Just place the code below somewhere on your child's theme `functions.php` file.
* If you also wish to get a meta description tag in the header, uncomment the last few lines.
*
* @todo this only works for singulars (page, post, attachment page, etc.); not for archive/search pseudo-pages,
which do *not* have a unique identifier at the $wp_query level... that's (mostly) why SEO plugins include
a *lot* of code just to deal with those ...
*
* @author Gwyneth Llewelyn
* @license MIT
* @revision 2
*
**/
/**
* Attempt to get a canonical link on the header (gwyneth 20210526).
**/
add_action('wp_head', 'my_canonical_link');
function my_canonical_link() {
// needs to handle non-singular cases, which are a bit more tricky
if ( is_front_page() ) {
$canonical_url = get_home_url();
if ( ! is_main_site() ) { // add trailing slash for subsite home directories
$canonical_url = trailingslashit( $canonical_url );
}
} else {
$canonical_url = wp_get_canonical_url(); // can return false if post is unpublished
}
if ( empty( $canonical_url ) ) {
echo '<link rel="canonical" href="' . esc_url( $canonical_url ) . '" />' . PHP_EOL;
}
// Uncomment the code below if you *also* wish to add a meta description tag. WordPress does *not* place one
// by default; these days, they are pretty much useless for Google, but Bing and possibly Yandex still
// reads them (gwyneth 20210526)
/*
echo '<meta name="description" content="' . esc_html( is_single() ?
single_post_title( get_bloginfo( 'name' ) . " - " , false ) . ( has_excerpt() ? " - " . get_the_excerpt() : '' )
: get_bloginfo( 'name' ) . " - " . get_bloginfo( 'description' ) ) . '" />' . PHP_EOL;
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment