Skip to content

Instantly share code, notes, and snippets.

@jdevalk
Created September 14, 2011 18:55
Show Gist options
  • Save jdevalk/1217431 to your computer and use it in GitHub Desktop.
Save jdevalk/1217431 to your computer and use it in GitHub Desktop.
new rel_canonical function
<?php
// this would replace the rel_canonical function in wp-includes/link-template.php
/**
* Output rel=canonical
*
* @package WordPress
* @since 2.9.0
*/
function rel_canonical() {
$link = false;
if ( is_singular() ) {
$link = get_permalink( get_queried_object() );
if ( $page = get_query_var('page') && 1 != $page )
$link = user_trailingslashit( trailingslashit( $link ) . get_query_var( 'page' ) );
} else {
if ( is_front_page() ) {
$link = trailingslashit( get_bloginfo('url') );
} else if ( is_home() && get_option('show_on_front') == "page" ) {
$link = get_permalink( get_option( 'page_for_posts' ) );
} else if ( is_tax() || is_tag() || is_category() ) {
$term = get_queried_object();
$link = get_term_link( $term, $term->taxonomy );
} else if ( is_post_type_archive() ) {
$link = get_post_type_archive_link( get_post_type() );
} else if ( is_archive() ) {
if ( is_date() ) {
if ( is_day() ) {
$link = get_day_link( get_query_var('year'), get_query_var('monthnum'), get_query_var('day') );
} else if ( is_month() ) {
$link = get_month_link( get_query_var('year'), get_query_var('monthnum') );
} else if ( is_year() ) {
$link = get_year_link( get_query_var('year') );
}
}
}
if ( $link && $paged = get_query_var('paged') && $paged > 1 ) {
global $wp_rewrite;
$link = user_trailingslashit( trailingslashit( $link ) . trailingslashit( $wp_rewrite->pagination_base ) . $paged );
}
}
$link = apply_filters( 'rel_canonical', $link );
if ( $link )
echo "<link rel='canonical' href='$link' />\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment