Created
October 6, 2010 08:22
-
-
Save mikeschinkel/613011 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment