Advertisement
vtxyzzy

Get tags for all posts in categories

Aug 23rd, 2012
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.10 KB | None | 0 0
  1. <?php
  2. /* Retrieve all tags from posts in selected categories */
  3.  
  4. $cats = array('beaches','mountains');  // Must be an array even if only one category
  5. $cats_string = "'" . implode($cats,"','") . "'";
  6. $sql = <<<EOSQL
  7. SELECT DISTINCT t.*
  8. FROM $wpdb->posts p
  9. JOIN $wpdb->term_relationships tr ON p.ID = tr.object_id
  10. JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id
  11.        AND tt.taxonomy = 'post_tag')
  12. JOIN $wpdb->terms t ON tt.term_id = t.term_id
  13. WHERE
  14.    p.ID IN (
  15.       SELECT p2.ID
  16.       FROM $wpdb->posts p2
  17.       JOIN $wpdb->term_relationships tr2 ON p2.ID = tr2.object_id
  18.       JOIN $wpdb->term_taxonomy tt2 ON (tr2.term_taxonomy_id = tt2.term_taxonomy_id AND tt2.taxonomy = 'category')
  19.       JOIN $wpdb->terms t2 ON (tt2.term_id = t2.term_id AND t2.name IN ($cats_string))
  20.       WHERE p2.post_type = 'post'
  21.       AND p2.post_status = 'publish'
  22.       AND p2.post_date <= NOW()
  23.    )
  24. EOSQL;
  25.  
  26. $terms = $wpdb->get_results($sql);
  27.  
  28. print_r($terms);
  29.  
  30. echo "<br />";
  31. foreach ($terms as $term) {
  32.    echo "ID:$term->term_id NAME:$term->name SLUG:$term->slug<br />";
  33. }
  34.  
  35. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement