Skip to content

Instantly share code, notes, and snippets.

@germanny
Created December 6, 2012 22:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save germanny/4228913 to your computer and use it in GitHub Desktop.
Save germanny/4228913 to your computer and use it in GitHub Desktop.
Function to find grandchildren pages
/* ABSOLUTE ANCESTOR
Returns the absolute ancestor (parent, grandparent, great-grandparent if there is, etc.) of a post. The absolute ancestor is defined as a page that doesnt have further parents, that is, its post parent is '0'
****************************************************************************************************************************************/
function get_absolute_ancestor($post_id){
global $wpdb;
$parent = $wpdb->get_var("SELECT `post_parent` FROM $wpdb->posts WHERE `ID`= $post_id");
if($parent == 0) //Return from the recursion with the title of the absolute ancestor post.
return $wpdb->get_var("SELECT `post_name` FROM $wpdb->posts WHERE `ID`= $post_id");
return get_absolute_ancestor($parent);
}//ends function
<ul>
<?php
// This function creates the $grandchild_ids variable which we'll use later
// It's looking to see if the post parent has a post parent
$all = get_pages();
foreach($all as $all) {
if($all->post_parent) {
if( get_page($all->post_parent)->post_parent ) {
$tp = get_page($all->post_parent);
if( !get_page( $tp->post_parent )->post_parent) {
$grandchild_ids[] = $all->ID;
}
}
}
}
// Now we use that variable to get all those pages associated with the IDs in $grandchild_ids array
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => -1,
'post__in' => $grandchild_ids // Multiple Post Handling; conveniently uses an array
);
// Make our query
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
// Only keep this up if the absolute ancestor is the States page (page slug needed)
// get_absolute_ancestor function provided in this gist
if (get_absolute_ancestor($post->ID) == 'states') {
$cities .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
}
endwhile;
}
wp_reset_query();
// Now list 'em out
$list_elements = explode('</li>', $cities);
$num = count($list_elements)-1;
$col = 3; //SET THE NUMBER OF COLUMNS
$num_col = ceil($num/$col);
for( $i=1; $i<$col; $i++) { $list_elements[$i*$num_col] = '</ul><ul class="links_list">'.$list_elements[$i*$num_col]; }
$list = implode('</li>', $list_elements);
// Disco
?>
<ul class="links_list">
<?php echo $list; ?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment