Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Help, this is probably the best way to have control over the styling of the wp_tag_cloud ...

I was looking for a way to add size based classes to my tags within the tag cloud widget. The problem here is that this solution only works when hard coded into for example a template file, but not for the tag cloud widget.

I also found this snippet to add slug classes and they beautifully work right out of the box. I simply had to place them inside the function.php file.

I was trying to get solution one to work in the same way solution number two works, but with the size based class names instead of slug names or even both. However, I can't figure it out and need help. Thanks in advance.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

try this code:

add_filter ( 'wp_tag_cloud', 'tag_cloud_font_size_class' );  
function tag_cloud_font_size_class( $taglinks ) { 
    $tags = explode('</a>', $taglinks);
    $regex1 = "#(.*style='font-size:)(.*)((pt|px|em|pc|%);'.*)#e"; 
    $regex2 = "#(style='font-size:)(.*)((pt|px|em|pc|%);')#e";         
    $regex3 = "#(.*class=')(.*)(' title.*)#e";         
    foreach( $tags as $tag ) {         
        $size = preg_replace($regex1, "(''.round($2).'')", $tag ); //get the rounded font size       
        $tag = preg_replace($regex2, "('')", $tag ); //remove the inline font-size style
        $tag = preg_replace($regex3, "('$1tag-size-'.($size).' $2$3')", $tag ); //add .tag-size-{nr} class
        $tagn[] = $tag;
    }     
    $taglinks = implode('</a>', $tagn);     
return $taglinks; 
}

there might be more effective solutions, or a way to put it all into one regex; however it works (I am no expert in preg_replace()). can be used at the same time as the slug class filter.

share|improve this answer
    
Thanks Michael, it does work. I should probably start learning regular expressions. Really powerful stuff it seams. Do you mind me asking, how do you teach yourself (in general)? I find it hard giving myself challenges and thus I mostly look at code other people wrote, but the learning curve seams to be slow that way. Any thoughts? Thanks again. –  marcup Aug 18 '12 at 17:46
    
I am still learning as well; general sources to combat my ignorance are php.net and w3schools.com combined with a lot of 'trial and error'. –  Michael Aug 18 '12 at 17:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.