Conditional tag in Widget Logic for checking if top level page or if subpage

I’m using the Widget Logic plugin to show widgets on certain pages using WordPress Conditional Tags (or any general PHP code).

What I would like to do is only show a widget on child pages, not top level pages. I tried both of the following but they both return true on all pages (so the widget shows on all pages):

Read More
global $post; return ($post->post_parent != 0);

and

global $post; return ( is_page() && $post->post_parent );

Note I tried this for testing and the widget displays on page ID 61 and its children, not just on its children as I was expecting:

global $post; return ($post->post_parent=="61");

Any tips?

Thanks!

Related posts

2 comments

  1. You can find the answer on the plugin’s page at wordpress.org. Select the tab ‘Other Notes’. You will find it at the example list:

    global $post;
    
    // WP page that is a child of page 77
    return in_array(77, get_post_ancestors($post)); 
    

    Edit: As an alternative to your suggestions you may try

    global $post;
    return !empty(get_post_ancestors($post)); 
    

    This is an expensive call and should better be used for testing only. But I suspect that there might be something wrong with your page hierarchy. Is it possible that your top level page is not on root level?

  2. Apologies, turns out it was a problem with my theme – using get_posts to list child pages outside the loop without wp_reset_postdata. So a global $post; conflict I guess.

    global $post; return ($post->post_parent != 0); works fine.

Comments are closed.