public

  • Download Gist
latest-post-per-post-type-query.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
<?php
/*
 
latest-post-per-post-type-query.php
 
LatestPostPerPostTypeQuery class that extends WP_Query and provides the latest post for each post type passed
 
Author: Mike Schinkel (http://mikeschinkel.com)
 
Just drop this example into the root of your website and call directly to see it work.
Use the class in your plugins or themes.
 
In Answer To: http://wordpress.stackexchange.com/questions/2593/
 
Reference: http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
 
*/
 
include "wp-load.php";
 
class LatestPostPerPostTypeQuery extends WP_Query {
var $flag;
function __construct($args=array()) {
$this->LatestPostPerPostTypeQuery($args);
}
function LatestPostPerPostTypeQuery($args=array()) {
if (isset($args['post_type']) && !is_array($args['post_type']))
$args['post_type'] = explode(',',$args['post_type']);
$this->flag = true;
parent::query($args);
}
static function on_load() {
add_filter('posts_join',array(__CLASS__,'posts_join'),10,2);
}
static function posts_join($join,$query) {
if (isset($query->flag)) {
global $wpdb;
$join .=<<<SQL
INNER JOIN (
SELECT post_type,MAX(post_date) AS post_date
FROM {$wpdb->posts}
GROUP BY post_type
ORDER BY COUNT(*) DESC
) max_date ON max_date.post_type={$wpdb->posts}.post_type AND max_date.post_date={$wpdb->posts}.post_date
SQL;
}
return $join;
}
}
LatestPostPerPostTypeQuery::on_load();
?>
<ul>
<?php $query = new LatestPostPerPostTypeQuery(array('post_type'=>'eevents,winners,offers')); ?>
<?php while($query->have_posts()): $query->the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; ?>
</ul>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.