function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {}

Checks the given subset of the post hierarchy for hierarchy loops.
Prevents loops from forming and breaks those that it finds.


  • int $post_parent: ID of the parent for the post we’re checking.
  • $post_ID

Return values

returns:The new post_parent for the post.

Source code

function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {

	// Nothing fancy here - bail

	if ( !$post_parent )

		return 0;

	// New post can't cause a loop

	if ( empty( $post_ID ) )

		return $post_parent;

	// Can't be its own parent

	if ( $post_parent == $post_ID )

		return 0;

	// Now look for larger loops

	if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )

		return $post_parent; // No loop

	// Setting $post_parent to the given value causes a loop

	if ( isset( $loop[$post_ID] ) )

		return 0;

	// There's a loop, but it doesn't contain $post_ID.  Break the loop.

	foreach ( array_keys( $loop ) as $loop_member )

		wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );

	return $post_parent;



No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: