Create a 301 Redirect automatically when adding %category% in the permalink

admin2025-01-08  6

I was wondering what would be the best approach to set 301 redirects. I have around a thousand blog posts and 19 categories so individually setting them up is a challenge. Though setting up 19 possible category combinations is fine, I prefer to have them automatically work. The URL structure in my setting is /%postname%/. I also modify the permalink via this code.

function filter_post_link($permalink, $post) {
    if ($post->post_type != 'post' || has_category('webinars', $post->ID))
        return $permalink;
    return 'blog'.$permalink;
}
add_filter('pre_post_link', 'filter_post_link', 10, 2);

With that said, I currently have my website with something like example/blog/sample-post/. However, I will soon need it to have categories in the URL. It can be something as follows:

  • example/blog/cat1/sample-post/
  • example/blog/cat1/cat2/sample-post-2/
  • example/blog/cat1/cat2/cat3/sample-post-3/

If I change the URL structure to /%category%/%postname%/, both the old url and new url will work. For example, example/blog/sample-post/ and example/blog/cat1/sample-post/ work. Now I just need to make sure the old url will redirect to the new one. What would be the best way?


Update: Tried the following

function test_template_redir(){
    if (get_post()->post_type === 'post'){
        global $wp;
        $var = get_permalink( get_the_ID() ); //gets the full complete url
        $current_url = home_url(add_query_arg(array(), $wp->request));

        if($var != $current_url){
            wp_redirect( $var );
            exit;
        }
    }
}
add_action( 'template_redirect', 'test_template_redir' );

Problem is now I am getting redirected you too many times. as it's thinking it's the same page I think.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736269453a1351.html

最新回复(0)