Wordpress: how to find a page’s latest grandchild

In the context of the website redesign of the School of Computer Graphic Design that i teach in, i had the need to display on the frontpage a link to the latest grandchild of a page. It didn't turn out as easy as i thought, but i somehow managed it. Here is how.

I looked around for any built-in function or plugin but nothing suited my need. Eventually, i resorted to doing a specific query in the database.

Here is the query and the loop that uses the dataset, as they sit in my frontpage.php template. It results in displaying a link with the latest testimonial's image to make it stand out.

PHP:
  1. $querystr = "SELECT p3.*
  2.            
  3.             FROM $wpdb->posts p1
  4.             LEFT OUTER JOIN $wpdb->posts p2 ON p2.post_parent=p1.ID
  5.             LEFT OUTER JOIN $wpdb->posts p3 ON p3.post_parent=p2.ID
  6.             WHERE (p1.post_status = 'publish' AND p1.post_type = 'page' AND p1.ID ='28') AND (p3.post_status = 'publish' AND p3.post_type = 'page') ORDER BY p3.post_date DESC LIMIT 0,1";
  7.  
  8.  
  9.             $myposts = $wpdb->get_results($querystr, OBJECT);
  10.             if ($myposts) {
  11.  
  12.                 foreach($myposts as $post) :
  13.                     setup_postdata($post);
  14.                     $postimageurl = get_post_meta($post->ID, 'post-img', true);
  15.                     $postimageurl = ($postimageurl) ? $postimageurl : '/medias/img/temoignage-banner.jpg';
  16.                     ?>
  17.  
  18.             <div id="importantBanner" style="background-image:url(<?php bloginfo('url');
  19.                           echo $postimageurl; ?>);margin:0;padding:0;">
  20.                 <a style="border-width:0" href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>" id="temoignageLink">
  21.                     <span class="tradeGothic" style="display:block;padding:7px 0 0 20px;font-size:12pt"><?php the_title(); ?></span>
  22.                 </a>
  23.             </div>
  24.                 <?php endforeach; ?>
  25.                 <?  }
  26.             ?>

If you have any question, shoot!