选择父页面及其所有子页面,但不包括一个特定的子页面

时间:2021-09-01 作者:Ahsan Ramzan

大家好,希望一切都好。我需要一些建议。我需要选择父页面及其所有子页面,但不包括一个特定的子页面。你能告诉我如何排除特定的孩子吗?

```// Store Only Show For the Registered Users 
function woocommerce_store_private_redirect() {
global $post;
if (
    ! is_user_logged_in()
    && (is_woocommerce() || is_cart() || is_checkout() || is_product_category() || is_product_tag() || is_product() || is_tree(64) )
) {
    // feel free to customize the following line to suit your needs
    wp_redirect( site_url(\'mein-konto/\') );
    exit;
}
}
add_action(\'template_redirect\', \'woocommerce_store_private_redirect\');

function is_tree($pid) {      // $pid = The ID of the page we\'re looking for pages underneath
global $post;         // load details about this page

$pages = get_posts([
\'post_type\' => \'page\',
\'posts_per_page\' => -1,
\'post_parent\' => $pid, // the parent id you want the children from
\'post__not_in\' => [4419] // the id you want to exclude
]);


if(is_page()&& $pages) 
           return true;   // we\'re at the page or at a sub page
else 
           return false;  // we\'re elsewhere
};

1 个回复
SO网友:Sally CJ

您的代码中存在一些问题,例如:。$pages 将始终返回一个数组,即使没有返回空数组的结果,所以if ( is_page() && $pages ) return true; 不一定意味着<我们在the 第页或子页;。相反,它的意思是“我的朋友,我的朋友”;只要是一个页面(帖子类型page), 然后返回true;。

尽管如此,请尝试以下方法,即使所讨论的页面有一个子页面也可以:

// This function checks whether the current Page has the specified ID ($pid), or
// that the current Page is a direct or indirect child of $pid.
function is_tree( $pid ) {
    // ID of the specific child page that you want to exclude.
    $cid = 4419;

    // Bail early if we\'re not on a Page.
    if ( ! is_page() ) {
        return false;
    }

    $page_id = get_queried_object_id();
    $pid     = (int) $pid;

    // We\'re on the parent page.
    if ( $pid === $page_id ) {
        return true;
    }

    // We\'re on the **excluded child page**, so return false.
    if ( (int) $cid === $page_id ) {
        return false;
    }

    $pages = get_pages( array( \'child_of\' => $pid ) );

    // Check if we\'re on one of the other child pages.
    return in_array( $page_id, wp_list_pluck( $pages, \'ID\' ) );
}