0

I would like to show a page depending on whether it has a subpage or not.

That is, if you have subpages, do not display the subpages, only the parent page to which it belongs.

Something like this:

Books of science
  Book 1
  Book 2

Books of science fiction
  Book 1
  Book 2

I have a home page where I want to show all the books, that is, all the main pages:

Books of science
Books of science fiction

And the idea is, not to show the subpages because it doesn't make sense in my case.

Is it possible?

  • Could you give an example? First part of your question was clear, but then you lost me ;) What do you mean by "if you have subpages, do not display the subpages, only the parent page to which it belongs"? – Krzysiek Dróżdż Jun 3 '18 at 19:16
  • 1
    If it's a little confusing now that I've read it again, I just edited the question – Marifer Villarroel Jun 4 '18 at 18:48
0

This code will return an array with IDs of all pages having sub pages. Hope you were looking for it :)

$args = array(
    'post_type' => 'page',
    'post_status' => 'publish'
);
$parentPages = array(); // an empty array to store pages with childs
$pages = get_pages($args); 
// Looping through all pages and then we'll check for the pages with child
foreach($pages as $page) {
    if($page->post_parent != 0){ // checking if the page has any parent
        // checking if parent page isn't in our array already
        if(!in_array($page->post_parent, $parentPages)) { 
            array_push($parentPages, $page->post_parent);
        }
    }
}
print_r($parentPages);
  • Well.. It won't. It will do nothing more than generate some warnings and notices - $pages and $parentPages variables are not defined anywhere, so... – Krzysiek Dróżdż Jun 4 '18 at 5:52
  • just added the loop code also. hope it helps now. – Kashan Shah Jun 5 '18 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.