wp_check_term_hierarchy_for_loops() WordPress Function

The wp_check_term_hierarchy_for_loops() function is used to check if a given term has any children. If it does, it recursively checks each child to see if it has any children of its own, and so on. This function is used to prevent infinite loops when working with hierarchical data.

wp_check_term_hierarchy_for_loops( int $parent, int $term_id, string $taxonomy ) #

Checks the given subset of the term hierarchy for hierarchy loops.


Description

Prevents loops from forming and breaks those that it finds.

Attached to the ‘wp_update_term_parent’ filter.


Top ↑

Parameters

$parent

(int)(Required)term_id of the parent for the term we're checking.

$term_id

(int)(Required)The term we're checking.

$taxonomy

(string)(Required)The taxonomy of the term we're checking.


Top ↑

Return

(int) The new parent for the term.


Top ↑

Source

File: wp-includes/taxonomy.php

function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
	// Nothing fancy here - bail.
	if ( ! $parent ) {
		return 0;
	}

	// Can't be its own parent.
	if ( $parent === $term_id ) {
		return 0;
	}

	// Now look for larger loops.
	$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) );
	if ( ! $loop ) {
		return $parent; // No loop.
	}

	// Setting $parent to the given value causes a loop.
	if ( isset( $loop[ $term_id ] ) ) {
		return 0;
	}

	// There's a loop, but it doesn't contain $term_id. Break the loop.
	foreach ( array_keys( $loop ) as $loop_member ) {
		wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
	}

	return $parent;
}


Top ↑

Changelog

Changelog
VersionDescription
3.1.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More