小部件逻辑 - 显示在页面和所有孩子

I have problem with condition function in Widget Logic (worpdress). I would like to display menu on subpage and all child set to it.

I use this:

global $post; return (in_array(1959,get_post_ancestors($post)));

In this case it works on all child but no dispaly on subpage (1959).

I try also:

global $post; return (is_page('Offer') || ($post->post_parent=="1959"));

In this case it doesn't display on deeper child.

I resloved it by this:

global $post; return (in_array(1959,get_post_ancestors($post))) || (is_page('Offer'));

I see you've already found a solution to your question however I'd like to go over the details of why your original attempts didn't work and how the code could be improved.

Your first snippet is going to retrieve all ancestor pages of the page (post object) provided. If any of those ancestors match the page ID you've defined, it will return true. The current page isn't being tested so if you're on the page you're checking for it will still return false.

In your second attempt, you're checking the post_parent property which is only giving you the immediate parent ID. Any higher level pages aren't included.

My solution would be:

global $post;
$page_id = 1959; // the page ID you want to test against.

return ( is_page( $page_id ) || in_array( $page_id, get_post_ancestors( $post ) ) );

I'm checking is_page() first in an attempt to avoid running the more intensive get_post_ancestors() function. I'm also using a variable for the page ID which is passed into both tests avoiding confusion.

You could transform the code into a function to make it reusable.

function wpse_is_page_or_subpage( $page_id ) {
    global $post;
    return ( is_page( $page_id ) || in_array( $page_id, get_post_ancestors( $post ) ) );
}

Usage: wpse_is_page_or_subpage( 1959 );