wp_check_post_hierarchy_for_loops

Check the given subset of the post hierarchy for hierarchy loops.

Description

(int) wp_check_post_hierarchy_for_loops( (int) $post_parent, (int) $post_ID ); 

Prevents loops from forming and breaks those that it finds. Attached to the filter.

Returns (int)

The new post_parent for the post, 0 otherwise.

Parameters (2)

0. $post_parent (int)
ID of the parent for the post we're checking.
1. $post_id (int)
ID of the post we're checking.

Usage

  1. if ( !function_exists( 'wp_check_post_hierarchy_for_loops' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // ID of the parent for the post we're checking. 
  5. $post_parent = -1; 
  6.  
  7. // ID of the post we're checking. 
  8. $post_id = -1; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = wp_check_post_hierarchy_for_loops($post_parent, $post_id); 
  12.  

Defined (1)

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

/wp-includes/post.php  
  1. function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) { 
  2. // Nothing fancy here - bail. 
  3. if ( !$post_parent ) 
  4. return 0; 
  5.  
  6. // New post can't cause a loop. 
  7. if ( empty( $post_ID ) ) 
  8. return $post_parent; 
  9.  
  10. // Can't be its own parent. 
  11. if ( $post_parent == $post_ID ) 
  12. return 0; 
  13.  
  14. // Now look for larger loops. 
  15. if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) ) 
  16. return $post_parent; // No loop 
  17.  
  18. // Setting $post_parent to the given value causes a loop. 
  19. if ( isset( $loop[$post_ID] ) ) 
  20. return 0; 
  21.  
  22. // There's a loop, but it doesn't contain $post_ID. Break the loop. 
  23. foreach ( array_keys( $loop ) as $loop_member ) 
  24. wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) ); 
  25.  
  26. return $post_parent;