0

How can I query only those pages that DO NOT HAVE child pages?

E.g.:

  • Parent page 1
    • Child page 1
    • Child page 2
  • Parent page 2
  • Parent page 3
    • Child page 1
    • Child page 2
  • Parent page 4

I would like to show

  • Parent page 2
  • Parent page 4


    $newQuery = new WP_Query( array (
        'posts_per_page' => -1,
        'post_type' => 'page',
        // Solution?
    ) );

Thanks

2 Answers 2

1

the_dramatist's answer will give you only top-level pages that have no children, which matches the example given in your description.

However, if you want to get ALL leaf pages, use the following:

SELECT *
FROM $wpdb->posts
WHERE
    post_type = 'page' AND ID NOT in
    (
        SELECT ID
        FROM $wpdb->posts
        WHERE
            post_type = 'page' AND ID in
            (
                SELECT post_parent
                FROM $wpdb->posts
                WHERE post_type = 'page'
            )
    ) AND post_status = 'publish'
1

Well, your situation is very unusual, I tried some default ways but with a SQL based functions seemed right choice for me-

function the_dramatist_pages_not_own_child() {
    global $wpdb;
    $sql = "SELECT * 
        FROM   {$wpdb->posts} AS p 
        WHERE  p.post_type LIKE 'page' 
               AND p.post_parent LIKE 0 
               AND p.id NOT IN (SELECT post_parent 
                                FROM   wp_posts AS p 
                                WHERE  p.post_type = 'page' 
                                       AND p.post_parent != '0' 
                                GROUP  BY post_parent)";

    return $wpdb->get_results($sql);
}

When you call the the_dramatist_pages_not_own_child() it will return you all the posts as individual object which don't have child pages.

Hope that helps.

2
  • I know. I could not find anything, but it is a requirement I have for this project. Let me try that out.
    – carkod
    Feb 16, 2017 at 14:25
  • Is the above answer helped ?
    – CodeMascot
    Feb 16, 2017 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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