Skip to content

Instantly share code, notes, and snippets.

@Archie22is
Forked from Bobz-zg/redirect-wp-post.php
Created February 7, 2017 07:45
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 Archie22is/4fd1a196c23c61f74ac427f869af3bc5 to your computer and use it in GitHub Desktop.
Save Archie22is/4fd1a196c23c61f74ac427f869af3bc5 to your computer and use it in GitHub Desktop.
Redirects wordpress posts to new url: site.com/blog/post-name
<?php
/**
* Add new rewrite rule
*/
function create_new_url_querystring() {
add_rewrite_rule(
'blog/([^/]*)$',
'index.php?name=$matches[1]',
'top'
);
add_rewrite_tag('%blog%','([^/]*)');
}
add_action('init', 'create_new_url_querystring', 999 );
/**
* Modify post link
* This will print /blog/post-name instead of /post-name
*/
function append_query_string( $url, $post, $leavename ) {
if ( $post->post_type == 'post' ) {
$url = home_url( user_trailingslashit( "blog/$post->post_name" ) );
}
return $url;
}
add_filter( 'post_link', 'append_query_string', 10, 3 );
/**
* Redirect all posts to new url
* If you get error 'Too many redirects' or 'Redirect loop', then delete everything below
*/
function redirect_old_urls() {
if ( is_singular('post') ) {
global $post;
if ( strpos( $_SERVER['REQUEST_URI'], '/blog/') == false) {
wp_redirect( home_url( user_trailingslashit( "blog/$post->post_name" ) ), 301 );
exit();
}
}
}
add_filter( 'template_redirect', 'redirect_old_urls' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment