quick wordpress tip: how to get all tags with the number of posts

This is very useful in certain situations, where you want to draw your own tag cloud or show the number of posts beside each tags in your wordpress blog, i.e (php [10], javascript [3]). I was searching for the solution while ago and found wp_tag_clouds but that doesn’t return the number of posts for each of these tags. Shortly after that, found get_terms function which was a great relief actually. Because you can fetch all types of taxonomies with useful data. And the following code snippet solved my problem. Don’t forget to check the reference in codex.

[sourcecode lang=”php”]
$tags = get_terms( array("post_tag"), array("orderby"=>"count","order"=>"DESC"));
[/sourcecode]

This function will output something like the following
[sourcecode lang=”php”]
Array
(
[0] => stdClass Object
(
[term_id] => 11
[name] => php
[slug] => php
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => post_tag
[description] =>
[parent] => 0
[count] => 2
)
[1] => stdClass Object
(
[term_id] => 10
[name] => bingo
[slug] => bingo
[term_group] => 0
[term_taxonomy_id] => 10
[taxonomy] => post_tag
[description] =>
[parent] => 0
[count] => 1
)
[2] => stdClass Object
(
[term_id] => 12
[name] => javascript
[slug] => javascript
[term_group] => 0
[term_taxonomy_id] => 12
[taxonomy] => post_tag
[description] =>
[parent] => 0
[count] => 1
)
)
[/sourcecode]

Shameless Plug

We develop beautiful Admin Panel templates for the web application developers. Our recent product is “Bolt” which is responsive and built on top of Twitter’s bootstrap. Give it a try and let us know how do you like it.

Bolt Responsive Admin Panel Template for Developers
Bolt Responsive Admin Panel Template for Developers