In the example we need all of our articles to have the following schema:

  • Site URL
  • news
  • post name

But once the structure is changed, not all URLs are 404.

Hook template_redirect

The objective of the hook is to detect when a URL responds in 404, if this is the case we look for the slug of the post and if it corresponds to a post in the database we redirect it with our prefix.

It works with all prefixes!

 

function add_prefix() {
    global $wp;

    if(is_404()){
        $url = home_url( $wp->request );
        $segments = explode('/', parse_url($url, PHP_URL_PATH));
        $last_segment = end($segments);

        $post_slug = get_page_by_path($last_segment, OBJECT, 'post');
        if ($post_slug) {
            $post_id = $post_slug->ID;
            wp_redirect(( get_permalink($post_slug->ID) ), 301 );

        } else {
        //on sait jamais
        }
    }
}
add_filter( 'template_redirect', 'add_prefix' );
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Commentaires
Inline Feedbacks
View all comments