最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Exclude parent with child pages from WP_Query

programmeradmin0浏览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

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 badges
Add a comment  | 

2 Answers 2

Reset to default 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'

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.

发布评论

评论列表(0)

  1. 暂无评论