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
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
Share Improve this question edited Feb 16, 2017 at 13:36 carkod asked Feb 16, 2017 at 13:25 carkodcarkod 1237 bronze badges2 Answers
Reset to default 1the_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'
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.