programing

Query only parent pages in custom post type within loop

muds 2023. 9. 13. 23:59
반응형

Query only parent pages in custom post type within loop

I have this code below that querys posts and a post type:

 <?php
              $args = array('post_type' => 'apartmentlisting', 'parent' => 0, 'showposts'=>'-1');
              query_posts($args);
          ?>
          <?php if (have_posts()) : ?>
          <?php while (have_posts()) : the_post(); ?>

I am trying to query and return only the parent pages I have 10 parent pages and each have about 4-5 child pages. Any ways to return just the parents?

I have been digging on the codex on WP and on google and nothing. I only found articles on returning posts that have a parent of page ID XX.

Any ideas?

If there is no parent, the parent is zero. So your query should work. But the parameter is 'post_parent' not 'parent'. And 'showposts' is deprecated, use 'posts_per_page' instead. So try this:

$args = array('post_type' => 'apartmentlisting', 'post_parent' => 0, 'posts_per_page'=>'-1');

Have you looked into using the following:

<?php get_post_ancestors( $post ) ?>

where $post is the post id? You can get the post's ID with the following if you are within an action hook for the_content:

global $wp_query;
$page = $wp_query->page->ID;

ReferenceURL : https://stackoverflow.com/questions/8343544/query-only-parent-pages-in-custom-post-type-within-loop

반응형