Thursday, October 13, 2022
HomeWordPress DevelopmentCreate a 301 Redirect mechanically when including %class% within the permalink

Create a 301 Redirect mechanically when including %class% within the permalink


I used to be questioning what can be the perfect method to set 301 redirects. I’ve round a thousand weblog posts and 19 classes so individually setting them up is a problem. Although organising 19 doable class combos is okay, I desire to have them mechanically work. The URL construction in my setting is /%postname%/. I additionally modify the permalink through this code.

perform filter_post_link($permalink, $publish)  has_category('webinars', $post->ID))
        return $permalink;
    return 'weblog'.$permalink;

add_filter('pre_post_link', 'filter_post_link', 10, 2);

With that stated, I at the moment have my web site with one thing like instance.com/weblog/sample-post/. Nevertheless, I’ll quickly want it to have classes within the URL. It may be one thing as follows:

  • instance.com/weblog/cat1/sample-post/
  • instance.com/weblog/cat1/cat2/sample-post-2/
  • instance.com/weblog/cat1/cat2/cat3/sample-post-3/

If I modify the URL construction to /%class%/%postname%/, each the outdated url and new url will work. For instance, instance.com/weblog/sample-post/ and instance.com/weblog/cat1/sample-post/ work. Now I simply want to ensure the outdated url will redirect to the brand new one. What can be one of the simplest ways?


Replace: Tried the next

perform test_template_redir(){
    if (get_post()->post_type === 'publish'){
        international $wp;
        $var = get_permalink( get_the_ID() ); //will get the complete full 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' );

Drawback is now I get redirected you too many occasions. because it’s pondering it is the identical web page I feel.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments