Categories
Web

Adding images to the WordPress tag cloud and styling it with jQuery

This simple jQuery script will enable you to add images to the individual tags of the Wordpress tag cloud. With the script you can style the tag cloud too without touching the core (or Wordpress) functions.

This simple jQuery script will enable you to add images for the individual tags of the WordPress tag cloud (wp_tag_cloud). With the script you can style the tag cloud too without touching the core (or WordPress) functions. The image sizes correspond to the font sizes given by the tag cloud function of WordPress.

jQuery(function() {
    var imagesize;
    var alttxt;
    var linkhref;

    jQuery('a[class^="tag-link-"]').each(function() {
        imagesize = jQuery(this).css('font-size');
        alttxt = jQuery(this).text();
        linkhref = jQuery(this).attr('href');

        jQuery(this).before(
            '<a title="tag: ' +alttxt+ '" href="' +linkhref+ '">
             <img src="path/to/your/image" class="tagcloudimage"
             style="width:'+imagesize+';height:'+imagesize+';"
             alt="'+alttxt+' icon" /></a>'
        );
    });
});

First a couple of variables are stated. Then the jQuery action is targeted to the links of certain class. The class names of the tag cloud begin with the string ‘tag-link-‘ (and is followed by the id number of the tag in question). jQuery’s .each() function goes through each matched target.

Variables are filled with values from the link in question: the font-size, the visible link text and the link to the tag archive in the href attribute. After that completely new html is written before the tag link. In this case we create an image link and  fill it with corresponding variable values.

Function like this can be easily extended to further alter the outlook of the tag cloud; for instance make the text color change by the size value and so on. The script is best to place in the footer of your page (after the tag cloud anyway).