web-dev-qa-db-ja.com

子を持つ投稿(階層カスタム投稿タイプ)を検索する方法は?

階層型のカスタム投稿タイプで投稿をクエリする方法を見つけようとしています。おそらく、子投稿を持つWP_Queryを使用します。 WP_Query引数に'post_parent' => 0を設定することで、子を持たないすべてのページを取得できますが、子ではないすべての投稿が返されます。子の投稿がある投稿のみが必要です。

1
JPollock

post_parent__not_inパラメータを使用できます。

$args = array( 
           'post_type'           => 'cpt',
           'post_parent__not_in' => array( 0 ) 
);
$query = new WP_Query( $args );

タイプcpt投稿を取得する。

生成されたSQLにはこの部分が含まれます。

wp_posts.post_parent NOT IN (0)
1
birgire

私はあなたの要求を理解している限り、これがあなたが必要としているものだと思います。

私はコードを文書化しました、それを通って行ってください。

<?php
/*
Idea:   Collecting all the posts child posts by --->'post_parent__not_in' => array( 0 )<--- 
        in wp_query. Then find their parent posts by eliminating duplicates.
*/

    $query_array = array(
            //Change this post type to your Custom-Post-Type.
        'post_type' => 'news',
            //Showing all posts
        'posts_per_page' => -1, 
            //Giving all child posts only
        'post_parent__not_in' => array( 0 ) 
        );

    $the_query = new WP_Query($query_array);
        //Array to collect all parent posts
    $collect_parents = array();
    while($the_query->have_posts()):
        $the_query->the_post();
            //if condition is used to eliminate duplicates, generated by same child post of parent.
        if(!in_array($post->post_parent, $collect_parents)){
            //$collect_parents contains all the parent post id's
            $collect_parents[] = $post->post_parent;
        }

    endwhile;
        //Printing all the parent posts
    foreach($collect_parents as $parent){
        ?>
        <!-- Printing parent post title -->
        <h2><a href="<?php echo get_permalink($parent ); ?>"> <?php echo get_the_title($parent); ?></a></h2>
        <!-- Printing parent post content -->
        <p><?php echo get_post_field( 'post_content', $parent); ?></p>
        <?php
    }
?>
0
Sudeep K Rana