Question

I'm currently working a project where the pages and their hierarchy mimic categories, the query on each "category page" works fine, however at the top level I wish to query all the grandchildren pages, and skip the child pages.
In another question on here asking the same question they were pointed to look a Search for Children and Grandchildren

However, the code is not resulting anything for me, the query doesn't return any errors just returns empty, take a look.

<div id="children">
<dl>
<?php query_posts('static=true&posts_per_page=-1&child_of='.$id.'&order=ASC'); ?>
<?php if(have_posts()) : while (have_posts()) : the_post(); ?>
<?php     $inner_query = new WP_Query("post_type=page&posts_per_page=-1&child_of={$id}&order=ASC");
while ($inner_query->have_posts()) : $inner_query->the_post(); ?>
<dt><a href="<?php the_permalink();?>"><?php the_title();?>:</a></dt>
<dd style=""><em><?php the_excerpt(); ?></em></dd>
<?php endwhile; endwhile; endif; ?>
</dl>
</div>

I'm guessing $id has been replaced by the_ID(); however I cannot see why this isn't returning any results.

Any ideas what is going wrong here?

Was it helpful?

Solution

I found the answer here. While I admit this works for my application, I'm not sure on what exactly the code is doing, sure, you're interrogating a query with another query to see if there are any grandchildren, however a little lost on the details of what the implode() is for.

<?php
// set the id of current page
$gen1_ids = get_the_ID(); 
// query the id for children (or at least that's what I think this query does)
$gen2 = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_parent IN ($gen1_ids) AND $wpdb->posts.post_type = 'page' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.ID ASC");
$gen2_ids = implode($gen2,', ');

//query children if they have children
$gen3 = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_parent IN ($gen2_ids) AND $wpdb->posts.post_type = 'page' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.ID ASC"); 
$gen3_ids = implode($gen3,', ');
$args=array(
  'post__in' => $gen3,
  'post_type' => 'page',
  'post_status' => 'publish',
  'posts_per_page' => -1,
  'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
  while ($my_query->have_posts()) : $my_query->the_post(); 

// Your while code here 

 endwhile; 
} //endif
wp_reset_query();  // Restore global post data stomped by the_post().

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top