您可以使用get_page_by_path()
获取页面的WP_Post
对象,然后使用该对象获取子页ID数组,使用get_children()
.
// First we\'ll create the list of posts (pages) to exclude.
$exclude = array();
$parent_page_obj = get_page_by_path( \'abc\' );
if ( ! empty( $parent_page_obj ) ) {
$parent_id = $parent_page_obj->ID;
// Adds the parent page to the $exclude array.
$exclude[] = $parent_id;
$args = array(
\'post_type\' => \'page\',
\'post_parent\' => $parent_id,
\'numberposts\' => -1,
);
$children = get_children( $args );
foreach ( $children as $child ) {
$exclude[] = $child->ID;
}
}
// Now you can use the $exclude array in your get_posts() call.
$get_posts_arg = array(
// All your existing arguments here.
//...
\'exclude\' => $exclude,
);
$my_posts = get_posts( $get_post_args );
获取所有子代和孙辈,是的,直到第n代,下面的代码使用递归获取子代的子代,直到子代用完为止。我已经在当地的WP安装中快速测试了它,它已经运行了5代。
它应该对您正在做的事情起作用,但请注意递归可能会导致无限循环,因此请在将其投入生产之前在非生产站点中进行测试。
/**
* Gets all the descendants of a give page slug.
*
* @param int|string $id The ID or slug of the topmost page.
* @param array $kids The array of kids already discovered. Optional.
* @return array The array of kids found in the current pass.
*/
function wpse365429_get_kids( $id, $kids = null ) {
if ( empty( $kids ) ) {
$kids = array();
}
if ( is_string( $id ) ) {
$obj = get_page_by_path( $id );
if ( ! empty( $obj ) ) {
$id = $obj->ID;
}
}
if ( ! in_array( $id, $kids ) ) {
$kids[] = $id;
}
$child_pages = get_children( $id );
if ( ! empty( $child_pages ) ) {
foreach ( $child_pages as $child ) {
$kids = wpse365429_get_kids( $child->ID, $kids );
}
}
return $kids;
}
$exclude = wpse365429_get_kids( \'abc\' );
// From this point, you can use the $exclude array as you did in the
// previous code snippet.