Reputation: 4976
Using Wordpress, I need to generate an array of tags(terms) from posts in a particular category.
For instance, if I have two categories, "apple" and "orange", I want an array of terms that are only used in posts in the apple category -- not in the orange category. (though, if a term is used in both, that should be included)
I've tried using a handful of wordpress functions, but none return what I want (including tag_cloud function). My guess is I'm left with a Query call ... but so far all my queries aren't giving me the list I want.
Thanks in advance for your help.
Upvotes: 0
Views: 1936
Reputation: 261
Here is how you can accomplish this using WordPress functions
<?php
$tags = array();
$posts = get_posts('category_name=new-cat&numberposts=-1'); //get all posts in category
foreach ($posts as $post){
$posttags = get_the_tags($post->ID); //check for tags
if ($posttags){
foreach ($posttags as $posttag){
$tags[$posttag->term_id] = $posttag->name; // add to array of tag ids => names
}
}
}
print_r($tags);
?>
This may be preferable to a raw sql query since those will often break when WordPress updates their database schema.
Upvotes: 4
Reputation: 30133
I'm not sure you can accomplish what you want using the functions WordPress provides. Here's an SQL query that seems to do what you want:
SELECT tag_terms.name, COUNT(wp_posts.ID) FROM wp_posts
INNER JOIN wp_term_relationships AS cat_term_relationships ON wp_posts.ID= cat_term_relationships.object_ID
INNER JOIN wp_term_taxonomy AS cat_term_taxonomy ON cat_term_relationships.term_taxonomy_id= cat_term_taxonomy.term_taxonomy_id
INNER JOIN wp_terms AS cat_terms ON cat_term_taxonomy.term_id= cat_terms.term_id
INNER JOIN wp_term_relationships AS tag_term_relationships ON wp_posts.ID= tag_term_relationships.object_ID
INNER JOIN wp_term_taxonomy AS tag_term_taxonomy ON tag_term_relationships.term_taxonomy_id= tag_term_taxonomy.term_taxonomy_id
INNER JOIN wp_terms AS tag_terms ON tag_term_taxonomy.term_id= tag_terms.term_id
WHERE cat_term_taxonomy.taxonomy='category' AND cat_terms.name='apple' AND tag_term_taxonomy.taxonomy='post_tag'
GROUP BY tag_terms.name
The gist of it is that you join the wp_posts table with the taxonomy tables a couple times to get the post IDs in your desired category and then join those IDs with the taxonomy tables a couple more times to get the related tags.
Upvotes: 1