How to Add Image Field to Taxonomy in WordPress

Taxonomy is useful to group things together. Usually, when we add a post in WordPress, we assign taxonomy to it. By doing this, we will have a group of posts that come under a certain taxonomy. Categories, Tags are the default taxonomies in WordPress. A user can also create their own taxonomy using the function register_taxonomy().

By default, Taxonomy comes with few fields – Name, Slug, and Description. Just like a featured image for post, WordPress does not provide an image field for taxonomy. But in some scenarios, you may want to have an image for your taxonomy. In this article, we study how to add the image field to taxonomy in WordPress and display it on the front end.

I am going to show you both approaches – with and without a plugin. The user can pick any one option they are comfortable with.

Add Image Field to Taxonomy with Plugin

To get started, you need to install and activate the Advanced Custom Fields plugin.

The Advanced custom field is a field builder that allows you to easily add fields to the post types, taxonomies in WordPress with only a few clicks. For our tutorial, I am going to add the image field to the categories and display them on the front end.

Upon plugin activation, go to the menu Custom Fields and click on the Add New button.

On the next page, add title, fields, conditions for the field group.

add-acf-field

As shown in the above screenshot, I have given a title, field label. The field name is automatically generated from the field label. Under the field type, I selected the option Image. This option acts as file upload which allows the use of a WordPress media uploader.

Scroll down on the same page, select Return Format as Image Array.

acf-return-format

Under the Location, for the Rules it needs to add a condition that will apply to the current field group. In our case, I choose Taxonomy as equal to Category.

acf-field-location

Once you are done with the above settings, save the changes.

Now, if we go to the category edit page, we will see the field for Image upload.

category-image

Now a user can upload the image for a category. Next, let’s see how to display this image on the front end.

Display Category Image On the Front End

Advanced custom fields plugin provides a method get_field() which is used for displaying field values. To display the category field value you need to pass a field name and ‘category_TERM_ID’. If you are showing a custom taxonomy field value then the second parameter would be ‘term_TERM_ID’. Please refer to plugin documentation.

Let’s say we have uploaded an image for the category which has an ID 7. Then to display the image, our code will be as follows.

<?php
$term_id = 7;
$image = get_field('category_image', 'category_'. $term_id); //'category_image' is our field name
echo '<img src="'.$image['url'].'" alt="'.$image['alt'].'" />';

The variable $image has an image path with sizes of a thumbnail, medium, and large. You can choose any size of the image as per your requirement. Print the $image variable and you will get all meta details about the image.

Add Image Field to Taxonomy without Plugin

We have seen how to add an image field to the taxonomy through a plugin. This approach is fine for a non-technical person. If you are a WordPress developer, then obviously you won’t want to use the plugin. Let’s do it programmatically.

To accomplish this task we need to use a few WordPress actions. First, we need to add an image field on the Category form. For this, add the code below to your functions.php file.

function taxonomy_add_custom_field() {
    ?>
    <div class="form-field term-image-wrap">
        <label for="cat-image"><?php _e( 'Image' ); ?></label>
        <p><a href="#" class="aw_upload_image_button button button-secondary"><?php _e('Upload Image'); ?></a></p>
        <input type="text" name="category_image" id="cat-image" value="" size="40" />
    </div>
    <?php
}
add_action( 'category_add_form_fields', 'taxonomy_add_custom_field', 10, 2 );

function taxonomy_edit_custom_field($term) {
    $image = get_term_meta($term->term_id, 'category_image', true);
    ?>
    <tr class="form-field term-image-wrap">
        <th scope="row"><label for="category_image"><?php _e( 'Image' ); ?></label></th>
        <td>
            <p><a href="#" class="aw_upload_image_button button button-secondary"><?php _e('Upload Image'); ?></a></p><br/>
            <input type="text" name="category_image" id="cat-image" value="<?php echo $image; ?>" size="40" />
        </td>
    </tr>
    <?php
}
add_action( 'category_edit_form_fields', 'taxonomy_edit_custom_field', 10, 2 );

Check out your Categories page and you will now see an Image field with an Upload button and input field. 

Upload and Store the Image

Next, what I am going to achieve is with a click of the Upload button, the admin media modal should open and the selected image path will be set in the input field. This value then saves to the ‘wp_termmeta’ table with a meta key ‘category_image’.

To use a WordPress media uploader you need to write JavaScript code. Create a js/awscript.js file and enqueue it.

function aw_include_script() {
 
    if ( ! did_action( 'wp_enqueue_media' ) ) {
        wp_enqueue_media();
    }
 
    wp_enqueue_script( 'awscript', get_stylesheet_directory_uri() . '/js/awscript.js', array('jquery'), null, false );
}
add_action( 'admin_enqueue_scripts', 'aw_include_script' );

In the awscript.js file, write the below JavaScript code which opens a media modal, allows you to choose the image, and inserts the image path into the input field.

jQuery(function($){
    $('body').on('click', '.aw_upload_image_button', function(e){
        e.preventDefault();
        aw_uploader = wp.media({
            title: 'Custom image',
            button: {
                text: 'Use this image'
            },
            multiple: false
        }).on('select', function() {
            var attachment = aw_uploader.state().get('selection').first().toJSON();
            $('#cat-image').val(attachment.url);
        })
        .open();
    });
});

To learn more about the admin media modal please refer to wp.media documentation.

Now you can pick up the image from a WordPress media library. Let’s save it through the code below.

function save_taxonomy_custom_meta_field( $term_id ) {
    if ( isset( $_POST['category_image'] ) ) {
        update_term_meta($term_id, 'category_image', $_POST['category_image']);
    }
}  
add_action( 'edited_category', 'save_taxonomy_custom_meta_field', 10, 2 );  
add_action( 'create_category', 'save_taxonomy_custom_meta_field', 10, 2 );

We are done with the manual process of adding an image field to the taxonomy. Finally, you can display the image on the front end as follows.

<?php
$term_id = 39;
$image = get_term_meta($term_id, 'category_image', true);
echo '<img src="'.$image.'" />';

I hope you understand how to add the image field to taxonomy in WordPress. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

3 thoughts on “How to Add Image Field to Taxonomy in WordPress

  1. Nice article and YT video ! Exactly what I needed. However I run across a problem.

    To whom it may concern :
    I could not select my own taxonomy for my CPT when assigning an IMG to it.
    My taxonomy “country” was not selectable. Only its instances (India, Morocco…). No interest whatsoever.
    You need to make sure you enable “custom fields” in the given CPT.
    Now it works.

Leave a Reply

Your email address will not be published.