wp_old_slug_redirect

Redirect old slugs to the correct permalink.

Description

wp_old_slug_redirect(); 

Attempts to find the current slug from the past slugs.


Usage

  1. if ( !function_exists( 'wp_old_slug_redirect' ) ) { 
  2. require_once ABSPATH . WPINC . '/query.php'; 
  3.  
  4.  
  5. // NOTICE! Understand what this does before running. 
  6. $result = wp_old_slug_redirect(); 
  7.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/query.php  
  1. function wp_old_slug_redirect() { 
  2. if ( is_404() && '' !== get_query_var( 'name' ) ) { 
  3. global $wpdb; 
  4.  
  5. // Guess the current post_type based on the query vars. 
  6. if ( get_query_var( 'post_type' ) ) { 
  7. $post_type = get_query_var( 'post_type' ); 
  8. } elseif ( get_query_var( 'attachment' ) ) { 
  9. $post_type = 'attachment'; 
  10. } elseif ( get_query_var( 'pagename' ) ) { 
  11. $post_type = 'page'; 
  12. } else { 
  13. $post_type = 'post'; 
  14.  
  15. if ( is_array( $post_type ) ) { 
  16. if ( count( $post_type ) > 1 ) { 
  17. return; 
  18. $post_type = reset( $post_type ); 
  19.  
  20. // Do not attempt redirect for hierarchical post types 
  21. if ( is_post_type_hierarchical( $post_type ) ) { 
  22. return; 
  23.  
  24. $query = $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta, $wpdb->posts WHERE ID = post_id AND post_type = %s AND meta_key = '_wp_old_slug' AND meta_value = %s", $post_type, get_query_var( 'name' ) ); 
  25.  
  26. // if year, monthnum, or day have been specified, make our query more precise 
  27. // just in case there are multiple identical _wp_old_slug values 
  28. if ( get_query_var( 'year' ) ) { 
  29. $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", get_query_var( 'year' ) ); 
  30. if ( get_query_var( 'monthnum' ) ) { 
  31. $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", get_query_var( 'monthnum' ) ); 
  32. if ( get_query_var( 'day' ) ) { 
  33. $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", get_query_var( 'day' ) ); 
  34.  
  35. $id = (int) $wpdb->get_var( $query ); 
  36.  
  37. if ( ! $id ) { 
  38. return; 
  39.  
  40. $link = get_permalink( $id ); 
  41.  
  42. if ( get_query_var( 'paged' ) > 1 ) { 
  43. $link = user_trailingslashit( trailingslashit( $link ) . 'page/' . get_query_var( 'paged' ) ); 
  44. } elseif( is_embed() ) { 
  45. $link = user_trailingslashit( trailingslashit( $link ) . 'embed' ); 
  46.  
  47. /** 
  48. * Filters the old slug redirect URL. 
  49. * @since 4.4.0 
  50. * @param string $link The redirect URL. 
  51. */ 
  52.  
  53. if ( ! $link ) { 
  54. return; 
  55.  
  56. wp_redirect( $link, 301 ); // Permanent redirect 
  57. exit;