Advertisement
vtxyzzy

Counts of Custom Post type by Custom Taxonomy

Mar 13th, 2012
657
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.86 KB | None | 0 0
  1. <?php
  2.  
  3. // Count custom post type by custom taxonomy
  4. $sql = "SELECT count(1) as post_count, t.name as status FROM $wpdb->posts p
  5. JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
  6. JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = 'home-status')
  7. JOIN $wpdb->terms t ON (tt.term_id = t.term_id)
  8. WHERE p.post_type = 'homes'
  9. AND (p.post_status = 'publish' OR p.post_status = 'private')
  10. AND p.post_date < NOW()
  11. GROUP BY t.name";
  12.  
  13. $rows = $wpdb->get_results($sql, ARRAY_A);
  14. $counts = array();
  15. $labels = array('For Sale' => 'for sale', 'Sold' => 'sold');
  16. foreach ($rows as $row) {
  17.    $counts[$row['status']] = $row['post_count'];
  18. }
  19. foreach (array_keys($labels) as $label) {
  20.    $count = $counts[$labels[$label]];
  21.    $text = ($count == 1) ? 'Home is' : 'Homes are';
  22.    echo "<p>$count $text $label</p>";
  23. }
  24.  
  25. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement