Post Pic

Get tags specific to a particular category on your WordPress blog

Althought WordPress allow you to do lots of things by default, it didn’t allow you to display tags based on a selected category. Here is an useful code to be able to do so.

Just paste this code wherever you need to display the list of tags that are specific to a particular category. Don't forget to replace the category name on line 2.

<?php
	query_posts('category_name=work');
	if (have_posts()) : while (have_posts()) : the_post();
        $posttags = get_the_tags();
		if ($posttags) {
			foreach($posttags as $tag) {
				$all_tags_arr[] = $tag -> name; //USING JUST $tag MAKING $all_tags_arr A MULTI-DIMENSIONAL ARRAY, WHICH DOES WORK WITH array_unique
			}
		}
	endwhile; endif; 

	$tags_arr = array_unique($all_tags_arr); //REMOVES DUPLICATES
	echo '<pre>'.print_r($tags_arr, true).'</pre>'; //OUTPUT FINAL TAGS FROM CATEGORY

?>

Thanks to WordPress Forums for the tip!

† RIP Michael Jackson †

6 Responses

Sep 01 2011 10:17

Hi,

I tried to add this code to a php widget but it doesn’t work. Instead of the tags the code is shown.
I tried several php widget but it just wouldn’t work…

I’m runing WP 3.2.1

Cheers
Thomas

Sep 06 2011 02:29

I’d also be interested in a solution that allows the tags to be displayed as links, on the page, as opposed to the current display in the tags. Thanks!

Apr 05 2012 18:40

I also am only getting an output of code as well :(

May 08 2012 19:08

Hi Thanks but i need something different like categories from specific tags :)

Please help.

Thanks

Apr 11 2013 18:30

Nice recipe!
And here’s the functions.php version:

function get_category_tags($category){

query_posts(‘category_name=’.$category);

if (have_posts()) : while (have_posts()) : the_post();
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$all_tags_arr[] = $tag -> name; //USING JUST $tag MAKING $all_tags_arr A MULTI-DIMENSIONAL ARRAY, WHICH DOES WORK WITH array_unique
}
}
endwhile; endif;

$tags_arr = array_unique($all_tags_arr); //REMOVES DUPLICATES

return $tags_arr; //OUTPUT FINAL TAGS FROM CATEGORY

}

Apr 15 2013 09:46

not working at all.

my error:
Warning: array_unique() expects parameter 1 to be array, null given in C:\wamp\www\wordpress\wp-content\themes\airspree\sidebar.php on line 58

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox