Snippet: Add Category, Tag or Taxonomy Picture

WordPress core support two entities for contents one is post and other is taxonomy. Most of you would think it should be post and pages. But, that is not true. post, pages, attachments and revisions are inherited from post. Taxonomy is a way of grouping and categorizing posts or custom post types. Well known built-in examples are categories, tags and links. WordPress provided media gallery attach images and photos to your posts but how about if you want to attach images to your categories? May be you have custom taxonomy e.g. Location taxonomy for an Event post type and you want to add an icon or photo to each location you add. This snippet will allow you to add a picture to all of your taxonomies or the ones you specify particularly.

Usage

wpds_tax_pic_url();
wpds_tax_pic_url($category->cat_ID);

Practically, in archive.php, you can use the wpds_tax_pic_url(); without any parameters it should display the URL of the attached image.

    if(wpds_tax_pic_url()){
      echo '<img src="'.wpds_tax_pic_url().'" />';
    }else{
      // other image or nothing.
    }

And in page.php or post.php, something following would work

    $terms = wp_get_post_terms($post_id, 'custom_taxonomy');
    foreach ($terms as $t) {
        if(wpds_tax_pic_url($t->term_id))
            echo '<img src="'.wpds_tax_pic_url($t->term_id).'" />';
    }

Snippet

add_action('admin_head', 'wpds_admin_head');
add_action('edit_term', 'wpds_save_tax_pic');
add_action('create_term', 'wpds_save_tax_pic');
function wpds_admin_head() {
    $taxonomies = get_taxonomies();
    //$taxonomies = array('category'); // uncomment and specify particular taxonomies you want to add image feature.
    if (is_array($taxonomies)) {
        foreach ($taxonomies as $z_taxonomy) {
            add_action($z_taxonomy . '_add_form_fields', 'wpds_tax_field');
            add_action($z_taxonomy . '_edit_form_fields', 'wpds_tax_field');
        }
    }
}

// add image field in add form
function wpds_tax_field($taxonomy) {
    wp_enqueue_style('thickbox');
    wp_enqueue_script('thickbox');
    if(empty($taxonomy)) {
        echo '<div class="form-field">
                <label for="wpds_tax_pic">Picture</label>
                <input type="text" name="wpds_tax_pic" id="wpds_tax_pic" value="" />
            </div>';
    }
    else{
        $wpds_tax_pic_url = get_option('wpds_tax_pic' . $taxonomy->term_id);
        echo '<tr class="form-field">
		<th scope="row" valign="top"><label for="wpds_tax_pic">Picture</label></th>
		<td><input type="text" name="wpds_tax_pic" id="wpds_tax_pic" value="' . $wpds_tax_pic_url . '" /><br />';
        if(!empty($wpds_tax_pic_url))
            echo '<img src="'.$wpds_tax_pic_url.'" style="max-width:200px;border: 1px solid #ccc;padding: 5px;box-shadow: 5px 5px 10px #ccc;margin-top: 10px;" >';
        echo '</td></tr>';        
    }
    echo '<script type="text/javascript">
	    jQuery(document).ready(function() {
                jQuery("#wpds_tax_pic").click(function() {
                    tb_show("", "media-upload.php?type=image&amp;TB_iframe=true");
                    return false;
                });
                window.send_to_editor = function(html) {
                    jQuery("#wpds_tax_pic").val( jQuery("img",html).attr("src") );
                    tb_remove();
                }
	    });
	</script>';
}

// save our taxonomy image while edit or save term
function wpds_save_tax_pic($term_id) {
    if (isset($_POST['wpds_tax_pic']))
        update_option('wpds_tax_pic' . $term_id, $_POST['wpds_tax_pic']);
}

// output taxonomy image url for the given term_id (NULL by default)
function wpds_tax_pic_url($term_id = NULL) {
    if ($term_id) 
        return get_option('wpds_tax_pic' . $term_id);
    elseif (is_category())
        return get_option('wpds_tax_pic' . get_query_var('cat')) ;
    elseif (is_tax()) {
        $current_term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
        return get_option('wpds_tax_pic' . $current_term->term_id);
    }
}

Result

Admin Category or Taxonomy Image

Admin Category or Taxonomy Image

16 Responses to Snippet: Add Category, Tag or Taxonomy Picture

  1. boоκmarκed!!, I really like уοur blog!

  2. S. Singh says:

    Could you please tell me, how to display category images in page template?

    • Mohsin Rasool says:

      As detailed above, you can use following code in your page template to fetch the category image.

      wpds_tax_pic_url($category->cat_ID);

  3. Mike says:

    Great piece of code! How would I get it to display the category image on the level above? For example on a “category” page showing lots of subcategories, I want the images of those subcategories shown, not the image of the category I’m in (if you get what I mean)

    • Mohsin Rasool says:

      You are probably fetching and displaying subcategories in a loop using WordPress get_categories function. Within the loop, you should pass category ID to wpds_tax_pic_url($category->ID) fetch its image.
      Hope it helps

  4. Matt Pritchett says:

    How would you make the call with a custom taxonomy on a page template while in the LOOP?

  5. xavierlight says:

    Please help me, how to display if category have image? example

    if(“category have image”){
    wpds_tax_pic_url($category->cat_ID);
    }else{
    other image
    }

    • Mohsin Rasool says:

      It would be simple. Just check if wpds_tax_pic_url returns empty string or not. As in your example

      if(wpds_tax_pic_url($category->cat_ID)){
      wpds_tax_pic_url($category->cat_ID);
      }else{
      other image
      }

  6. foxpc says:

    Thanks for the code! but i have two quasions.
    1. how can i remove image from term after i have selected some image?

    2. when i try to create new term without image i get this error:
    PHP Notice: has_cap was called with an argument that is deprecated since version 2.0! Usage of user levels by plugins and themes is deprecated. Use roles and capabilities instead. in functions.php on line 2923

    PHP Notice: Trying to get property of non-object in functions.php on line 370

    • Mohsin Rasool says:

      Glad, this snippet could help you.

      1. Empty the text box having path to image and save the term.
      2. Error is being raised where “has_cap” function is called which is not part of this code snippet. You need to verify arguments you are passing.

      • foxpc says:

        Hello Mohsin Rasool,
        thanks for the anaser.
        i know that i can just remove the link from the text box and then save it but it’s not so nice solution.
        if there was some “link” so when you click on it it remove the link from the text box and make save.

        about part 2, where i can find whats make this error to appear when i try to create new term.

        Thanks for help.

  7. Sem says:

    Thanks for the cool idea! Can you help with this PHP notice?

    “Notice: Trying to get property of non-object”

    $wpds_tax_pic_url = get_option( ‘wpds_tax_pic’ . $taxonomy->term_id );

    Thanks again :)

  8. Karin Olsson says:

    Thanks – works great

  9. Ksenia says:

    Thank you very much for this extremely useful snippet! It saved me a lot of time and saved me from a huge headache! I successfully added featured images support for custom taxonomies.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>