Skip to content

Instantly share code, notes, and snippets.

@swinggraphics
Last active February 10, 2025 17:03
Show Gist options
  • Save swinggraphics/397346a6ca9221646b44e23e644c7340 to your computer and use it in GitHub Desktop.
Save swinggraphics/397346a6ca9221646b44e23e644c7340 to your computer and use it in GitHub Desktop.
Redirect posts to canonical URL when accessed via secondary category URL slugs
<?php
/*
Plugin Name: Redirect to Canonical
Description: Redirect posts to canonical URL when accessed via secondary category URL slugs.
Version: 1.0
Author: Greg Perham
License: GPL2
*/
defined( 'ABSPATH' ) || exit;
/* https://wordpress.stackexchange.com/questions/19290/how-can-i-force-wordpress-to-redirect-to-canonical-permalinks#answer-410192 */
add_action( 'template_redirect', 'r2c_canonical_redirect' );
function r2c_canonical_redirect() {
if ( is_singular( 'post' ) ) {
global $wp;
$wp->parse_request();
$current_url = trim( home_url( $wp->request ), '/' );
$canonical = wp_get_canonical_url();
$surl = trim( $canonical, '/' );
if ( $current_url != $surl ) {
wp_redirect( $canonical, 301 );
exit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment