Wordpress: Counting total number of times tags are used Wordpress: Counting total number of times tags are used wordpress wordpress

Wordpress: Counting total number of times tags are used


Really, first thing you need to do is build a list of terms that are used, then get the counts. Both of these can be done in a single database query.

$taxonomy = 'post_tag'; //the post type you want to look upglobal $wpdb; //get instance of database connection$sql = $wpdb->prepare("SELECT terms.name,taxonomy.count        FROM wp_terms AS terms         INNER JOIN wp_term_taxonomy AS taxonomy ON (terms.term_id = taxonomy.term_id)        WHERE taxonomy = %s;",$taxonomy);$results = $wpdb->get_results($sql);if ( $results ){    foreach ( $results as $result ){        echo('<p>'.$result->name.' has a count of '.$result->count.'</p>');    }   }

Please note: you should further refine the answer by using $wpdb->prefix instead of hard coding "wp_"...but if this is just for your own use and not for redistribution you don't need to worry about that.

EDIT:

Based on a comment on the original question, an alternate SQL could be:

$taxonomy = 'post_tag'; //the post type you want to look upglobal $wpdb; //get instance of database connection$sql = $wpdb->prepare("SELECT sum(taxonomy.count)        FROM wp_terms AS terms         INNER JOIN wp_term_taxonomy AS taxonomy ON (terms.term_id = taxonomy.term_id)        WHERE taxonomy = %s;",$taxonomy);$result = $wpdb->get_var($sql);echo("There are a total of $result tag matches");

A note: If you have 2 posts each using 3 different tags, you will get a result of 6 (which is what you wanted in your comment...but not what others might want).