函数文档

wp_check_term_hierarchy_for_loops()

💡 云策文档标注

概述

wp_check_term_hierarchy_for_loops() 函数用于检查术语层次结构中的循环,防止循环形成并打破发现的循环。它附加到 'wp_update_term_parent' 过滤器。

关键要点

  • 函数检查给定术语层次结构子集是否存在循环,确保术语父子关系不形成闭环。
  • 参数包括 $parent_term(父术语ID)、$term_id(检查的术语ID)和 $taxonomy(术语的分类法)。
  • 返回值为新的父术语ID,如果检测到循环则可能返回0以中断循环。
  • 函数内部调用 wp_find_hierarchy_loop() 来查找循环,并使用 wp_update_term() 打破循环。
  • 此函数自 WordPress 3.1.0 版本引入。

代码示例

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

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

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

	// Setting $parent_term 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_term;
}

注意事项

  • 函数在 'wp_update_term_parent' 过滤器上调用,自动处理术语更新时的循环检查。
  • 如果检测到循环,函数会通过将相关术语的父级设置为0来打破循环,确保数据一致性。
  • 开发者应确保正确传递参数,避免在自定义代码中手动创建循环。

📄 原文内容

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.

Parameters

$parent_termintrequired
term_id of the parent for the term we’re checking.
$term_idintrequired
The term we’re checking.
$taxonomystringrequired
The taxonomy of the term we’re checking.

Return

int The new parent for the term.

Source

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

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

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

	// Setting $parent_term 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_term;
}

Changelog

Version Description
3.1.0 Introduced.