Journal of a Web Professional in Brussels

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

If you have any question, shoot!

[ad#horizontal_inline]

The Conversation

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Belgians do IT better _