WordPress WP_Query - Parent Query Pages Only

I use WP_Query to query my custom posts like message. This custom post type has parent and child pages. I am trying to pull out the first parent page. How can I do it?

+4
source share
3 answers
$parent_only_query = new WP_Query(array( 'post_type' => 'my-custom-post-type', 'post_parent' => 0 )); while ($parent_only_query->have_posts()){ $parent_only_query->the_post(); // etc... } wp_reset_query(); // if you're not in your main loop! otherwise you can skip this 
+17
source

You can achieve this functionality by executing a database query;

 <?php $parent_posts= $wpdb->get_results( "SELECT ID, post_title FROM $wpdb->posts WHERE post_parent=0 AND post_type='page' AND post_status='publish' ORDER BY menu_order ASC" ); foreach($parent_posts as $record){ ?> <a href="<?php echo get_permalink($record->ID) ?>" > <h1><?php echo $record->post_title; ?></h1> </a> <p><?php echo $record->post_title;?></p> <?php } ?> 

Note: - $wpdb is a global variable.

+2
source

After you run your request and you are looped over it, you can access the parent id of each message using $post->post_parent , and if it is not null, you can get this message with get_post() :

 <?php if($post->post_parent): $parent = get_post($post->post_parent); ?> <h2><?=$parent->post_title;?></h2> <p><?=$parent->post_content;?></p> <?php endif; ?> 
+1
source

Source: https://habr.com/ru/post/1345033/


All Articles