meetsos

Redirect /%category%/%postname%/ to /%postname%/

Feb 11th, 2021 (edited)
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.66 KB | None | 0 0
  1. // REDIRECT /%category%/%postname%/ to /%postname%/ (for old posts links in social, after change permalinks)
  2. add_filter( '404_template', 'custom_redirect_to_category' );
  3.  
  4. function custom_redirect_to_category($template) {
  5.  
  6.     if ( ! is_404() ){
  7.         return $template;
  8.     }
  9.  
  10.     global $wp_rewrite;
  11.     global $wp_query;
  12.  
  13.     if ( '/%category%/%postname%/' !== $wp_rewrite->permalink_structure ){
  14.         return $template;
  15.     }  
  16.  
  17.     if ( ! $post = get_page_by_path( $wp_query->query['category_name'], OBJECT, 'post' ) ){
  18.         return $template;  
  19.     }
  20.  
  21.     $permalink = get_permalink( $post->ID );
  22.     wp_redirect( $permalink, 301 );
  23.     exit;
  24. }
Add Comment
Please, Sign In to add comment