6
votes

I'm using a WP_Query to query my custom post type posts. This custom post type has parent and children pages. I'm trying to pull the first parent page. How would I do this?

3

3 Answers

31
votes
$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
2
votes

You can achieve this functionality by making a query to database;

<?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 global variable.

1
votes

Once you have run your query and you are looping through it, you can access the ID of the parent of each post with $post->post_parent, and if that is not null you can get that post content 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;
?>