wp_check_for_changed_slugs

Check for changed slugs for published post objects and save the old slug.

Description

wp_check_for_changed_slugs( (int) $post_id, (WP_Post) $post, (WP_Post) $post_before ); 

The function is used when a post object of any type is updated, by comparing the current and previous post objects.

If the slug was changed and not already part of the old slugs then it will be added to the post meta field ('_wp_old_slug') for storing old slugs for that post.

The most logically usage of this function is redirecting changed post objects, so that those that linked to an changed post will be redirected to the new post.

Parameters (3)

0. $post_id (int)
The post id.
1. $post (WP_Post)
The Post Object
2. $post_before (WP_Post)
The Previous Post Object

Usage

  1. if ( !function_exists( 'wp_check_for_changed_slugs' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // The post id. 
  5. $post_id = -1; 
  6.  
  7. // The Post Object 
  8. $post = null; 
  9.  
  10. // The Previous Post Object 
  11. $post_before = null; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = wp_check_for_changed_slugs($post_id, $post, $post_before); 
  15.  

Defined (1)

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

/wp-includes/post.php  
  1. function wp_check_for_changed_slugs( $post_id, $post, $post_before ) { 
  2. // Don't bother if it hasn't changed. 
  3. if ( $post->post_name == $post_before->post_name ) { 
  4. return; 
  5.  
  6. // We're only concerned with published, non-hierarchical objects. 
  7. if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) { 
  8. return; 
  9.  
  10. $old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' ); 
  11.  
  12. // If we haven't added this old slug before, add it now. 
  13. if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs ) ) { 
  14. add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name ); 
  15.  
  16. // If the new slug was used previously, delete it from the list. 
  17. if ( in_array( $post->post_name, $old_slugs ) ) { 
  18. delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );