Get tag IDs for a specific category in WordPress (MySQL), order by popular

If you want to get tags based on category, and order by tag count value, here is the query:

Assuming that the category ID is 123456

SELECT wp_term_taxonomy.term_id as term_id, COUNT(*) AS count FROM wp_term_taxonomy INNER JOIN wp_term_relationships ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_id WHERE wp_term_taxonomy.taxonomy = 'post_tag' AND wp_term_relationships.object_id IN ( SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 123456 ) GROUP BY term_id ORDER BY `wp_term_taxonomy`.`term_id` DESC

Will return (sample):

term_idcount
1235
3213

Notice that the count here is not default WordPress term count, but count of returning rows of same values, for posts under caterogy of 123456.

Warning: This is the raw query phpMyadmin, you need to do all the security prepare stuffs.

There is another version using the built-in WordPress functions:

https://wordpress.stackexchange.com/questions/75017/get-tags-specific-category

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>