函数文档

wp_check_post_hierarchy_for_loops()

💡 云策文档标注

概述

wp_check_post_hierarchy_for_loops() 函数用于检查文章层级中的循环,防止循环形成并打破发现的循环。它通过 'wp_insert_post_parent' 过滤器附加,确保文章父级设置不会导致无限循环。

关键要点

  • 函数检查给定的文章父级和文章ID,以检测层级循环。
  • 如果检测到循环,函数会返回新的 post_parent 值或打破循环。
  • 函数内部调用 wp_find_hierarchy_loop() 来查找循环,并使用 wp_update_post() 打破循环。

代码示例

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 ( ! $post_id ) {
        return $post_parent;
    }

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

    // Now look for larger loops.
    $loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_id, $post_parent );
    if ( ! $loop ) {
        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;
}

注意事项

  • 函数需要两个参数:$post_parent(父文章ID)和 $post_id(当前文章ID),均为必需整数。
  • 返回值是新的 post_parent 值,如果检测到循环则可能返回 0。
  • 函数在 WordPress 3.1.0 版本中引入,用于维护文章层级结构的完整性。

📄 原文内容

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

Description

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

See also

Parameters

$post_parentintrequired
ID of the parent for the post we’re checking.
$post_idintrequired
ID of the post we’re checking.

Return

int The new post_parent for the post, 0 otherwise.

Source

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 ( ! $post_id ) {
		return $post_parent;
	}

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

	// Now look for larger loops.
	$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_id, $post_parent );
	if ( ! $loop ) {
		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;
}

Changelog

Version Description
3.1.0 Introduced.