Skip to content

Instantly share code, notes, and snippets.

@birgire
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save birgire/4becd6a623ecf1492bba to your computer and use it in GitHub Desktop.
Save birgire/4becd6a623ecf1492bba to your computer and use it in GitHub Desktop.
Fetch taxonomy terms statistics for all posts before due date, with a single database query.
/**
* Fetch taxonomy terms statistics for all posts before due date, with a single database query.
*
* Assumes that the 'due' values are saved as YYYYMMDD
*
* @see http://www.wpquestions.com/question/showChronoLoggedIn/id/9770
* @param string $taxonomy
* @param string $meta_key
* @return mixed Database query results
* @version 0.0.2
*/
function get_tax_terms_stats_before_due_date( $taxonomy, $meta_key )
{
global $wpdb;
$sql ="
SELECT COUNT(1) as postscount, t.term_id, t.name, t.slug, tt.taxonomy
FROM tfl_term_relationships tr
INNER JOIN {$wpdb->posts} p ON p.ID = tr.object_id
INNER JOIN {$wpdb->postmeta} pm ON ( p.ID = pm.post_id AND pm.meta_key = '%s' )
INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN {$wpdb->terms} t ON tt.term_id = t.term_id
WHERE
1*pm.meta_value > %d
AND p.post_status = 'publish'
AND tt.taxonomy = '%s'
GROUP BY t.term_id
ORDER BY postscount DESC
";
return $wpdb->get_results( $wpdb->prepare( $sql, $meta_key, date( 'Ymd' ), $taxonomy ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment