好的,我找到了一个方法。我希望它能帮助那些面临同样问题的人。如果您想根据父slug或ID(两者都可以)和给定的帖子类型(custom\\u post\\u type或页面或帖子)仅针对特定帖子。
在这种情况下,仅影响:
my_custom_post_type_name
-first_page (example.com/my_custom_post_type_name/first_page)
--first_page_child
---first_page_grandchild
--first_page_child_2
但不影响:
my_custom_post_type_name
-second_page
--second_page_child
---second_page_grandchild
以下是您需要的功能:
function get_posts_children($CPT, $post_slug){
//check if the $post_slug is a string.
if(is_string($post_slug)){
$parent_page_obj = get_page_by_path( $post_slug, \'\', $CPT );
if ( ! empty( $parent_page_obj ) ) {
$parent_id = $parent_page_obj->ID; //assign $parent_id to be an integer.
}
}
//check if the $post_slug is an integer(ID) for when the function is calling itself (for grandchildren check).
if( is_int ( $post_slug ) ){
$parent_id = $post_slug; //if $post_slug is an integer assign it to $parent_id
}
$group = array();
$group[] = $parent_id; //add $post_slug (in this case coverted to $parent_id already) to be a part of the array. (you can remove it if you only need the children and grandchildren of a given post ID or slug).
// grab the direct children of the post by given $post_slug or post ID.
$direct_children = get_posts(
array(
\'numberposts\' => -1,
\'post_status\' => \'publish\',
\'post_type\' => $CPT,
\'post_parent\' => $parent_id
)
);
// now grab the grandchildren
foreach( $direct_children as $child ){
$grandchildren = get_posts_children($CPT, $child->ID); // call the same function again for grandchildren
if( ! empty($grandchildren) ) {
$group = array_merge($group, $grandchildren); // merge the grandchildren into the children array
}
}
$group = array_merge($group, $direct_children); // merge in the $direct_children into the group array.
return $group; //return an array of all the IDs found.
}
然后从任何地方定位这些帖子/页面,并将其与您需要的当前显示的页面/帖子进行比较:
global $post;
if(in_array($post->ID, get_posts_children(\'my_custom_post_type_name\', \'first_page\'))){
//do something. If the current displayed page is \'first_page\' OR \'first_page_child\' OR \'first_page_grandchild\' OR \'first_page_grandchild\'.
//But it will not affect if the current displayed page is \'second_page\' OR \'second_page_child\' OR \'second_page_grandchild\'.
//This is handy to do many things.
//I\'m currently using it to redirect some specific custom user capabilities from restricted areas.
//But allowing them to access second_page and its children for that matter.
}