How to Use ACF to Dynamically Color Taxonomy Labels in Elementor Loop

David Denedo

David Denedo

Published on .

Table of Content

Introduction

Creating a visual distinction among various groups of loop items can significantly improve the user experience on your website. This tutorial will guide you on how to add coloured labels to your loop grids. Their taxonomy term will serve as the basis for the labels. This can be especially useful to distinguish between free and paid courses. It can also help to differentiate between different tiers of premium services that your company offers.

This tutorial uses Elementor Pro, Advanced Custom Fields (ACF), and a code snippets plugin or child theme. Elementor provides a range of features. These include flexbox containers, loop grids, loop carousels, and taxonomy filters. However, there’s room for improvement, especially in expanding the dynamic tags.

In this tutorial, we’ll use Elementor Pro to create the loop grid. We’ll use ACF to create the custom post type (CPT) and custom taxonomy. We’ll also use ACF to create the colour picker meta field for the taxonomy label colour.

Check out the tutorial video and share your thoughts in the comment section below.

PHP Code Snippet

Below is the PHP snippet used to create the [cat-color] shortcode. It dynamically retrieves the colour meta field “resource-type-color” within the custom taxonomy “resource-type” for the current post:

function cat_color_shortcode() {
    global $post;
    $post_id = $post->ID;
    $term_list = wp_get_post_terms($post_id, 'resource-type', array('fields' => 'ids'));
    $term_id = (int)$term_list[0];
    $color = get_field('resource-type-color', 'term_'.$term_id);
    if($color) {
        return $color;
    } else {
        return '';
    }
}
add_shortcode('cat-color', 'cat_color_shortcode');

Updated PHP Code Snippet

Below is an improved PHP Snippet. It is more customisable and useful when you want to display many term meta fields on your page. The syntax for the shortcode is [dd-term-meta tax="your-taxonomy-name" field="your-term-meta-field"]. Use the shortcode widget or the shortcode dynamic tag to add the term meta field to your page.

<?php
function dd_term_meta_shortcode($atts) {
    // Extract shortcode attributes
    $atts = shortcode_atts(
        array(
            'tax'   => 'category',          // Default taxonomy
            'field' => '',    // Default field
        ),
        $atts,
        'dd-term-meta'
    );

    global $post;
    $post_id = $post->ID;

    // Taxonomy Info
    $dd_taxonomy_slug = sanitize_text_field($atts['tax']);
    $dd_term_meta_field = sanitize_text_field($atts['field']);

    // Get an array of term IDs
    $term_list = wp_get_post_terms($post_id, $dd_taxonomy_slug, array('fields' => 'ids'));

    // Check if there are terms
    if (!empty($term_list)) {
        $term_id = (int) $term_list[0];

        // Get term meta using ACF
        $dd_term_meta = get_field($dd_term_meta_field, 'term_' . $term_id);

        // Check if term meta exists
        if ($dd_term_meta) {
            return $dd_term_meta;
        } else {
            return '';
        }
    }

    return '';
}

add_shortcode('dd-term-meta', 'dd_term_meta_shortcode');

Adding the shortcode as custom attribute

Elementor does not yet offer the option to use a shortcode as a dynamic tag for the background colour. Unfortunately. To overcome this limitation, we’ll use the Custom Attribute instead. Follow the steps below:

  1. Navigate to the Advanced Tab of the required heading widget.
  2. In the “Attributes” accordion, click on the dynamic tag icon.
  3. Choose the “Shortcode” dynamic tag, and click on the wrench icon.
  4. Insert the shortcode [cat-color] under the Settings accordion.
  5. Under the Advanced Accordion, in the “Before” input, add the following code: style|background-color:
  6. Save and exit.
Click on the dynamic tag under the Attributes Section
Add the shortcode
Add the before text

If you’ve followed these steps correctly, you’ll successfully apply coloured labels to your loop grid.

17 comments

  • Hi David,

    just a quick THANK YOU for this tutorial, it worked really well!
    I’ve never even thought of putting something like “style|background-color:” in the “Before” input section there. This will be very useful in many cases!

    Cheers from Berlin
    Alex

  • Pedro Simao

    Hi David,

    Great tutorial! Thank you so much for sharing.
    I was wondering how I could target the div’s element to change the text color.
    Any ideas?

    Thanks in advance

  • Very cool functionality. Thanks for the tutorial. Can a similar strategy be used to display images, Google Maps, etc.? As a summary:

    I’m creating a site for my musician son with a custom ACF CPT called “Gigs” to display his upcoming shows. I’ve also created a custom ACF Taxonomy called “Locations” to enable a list of venues to be attached to the “Gigs” CPT. The “Locations” taxonomy has its own ACF custom fields (Image, Google Map, etc.) that would be equivalent to this “category-color” example.

    That said, I cannot figure out how to display these other types of fields. I guess they are called “terms_meta” because they are fields that reside inside the taxonomy. I’ve tried code snippets that either don’t work or crash the site. I’m not developer, but rather a Beginner Dad Designer that is trying to create a beautiful and, most importantly, highly functional dynamic data driven site with minimal plugins.

    Your insight is greatly appreciated. Thanks in advance!

    • Hi Todd

      It’s nice to hear what you’re trying to do for your son.

      Yes, they are called terms_meta. I believe this code should be able to retrieve a Google Maps point as well. However, for images, it’ll be slightly different. You’ll need to use wp_get_attachment_image().

      What I’d recommend is using a plugin like Dynamic.ooo’s Dynamic Shortcodes. I’m currently conducting an extensive test on the plugin, and it looks really solid for retrieving any kind of dynamic data. The nice thing is that it works with several page builders like Elementor and Gutenberg.

      But, I’ll look into updating the current code snippet to allow you to easily use the shortcode to retrieve any term meta field by simply calling the shortcode using the taxonomy name and field name as keyargs. Something like [dd_term_meta tax=’term_name’ field=’field_name’].

      • David — Thanks for the quick reply. I look forward to hearing more about the Dynamic.ooo Shortcode plugin — although I’m really trying to minimize plugins … perhaps too much, I don’t know!

        And, an update to the current “cat-color” code snippet would be amazing! I’ll stay tuned.

        Cheers!

        • Hi Todd

          I’ve added an updated php snippet to easily retrieve different ACF term meta fields – https://daveden.co.uk/tutorials/dynamic-acf-taxonomy-label-color-in-elementor-loop/#updated-php-code-snippet.

          I have a video scheduled to upload tomorrow to show how to retrieve a list of taxonomy term images.

          Please let me know what you think.

          • David,
            This is awesome! I have it working to pull in an image and URL for my locations. Haven’t figured out the ACF Google Map yet — likely more complex because that custom field is returning an array of data (latitude, longitude, zoom, address, …). I watched your new video as well & learned even more. Until watching that I didn’t realize that the attributes were actually editable in the Shortcode itself. I placed that data into the snippet. That works nicely too though because I could combine 2 fields into one Shortcode. For reference, I combined my Location Image and Location Link (URL) into a clickable image for the Location assigned to a “Gig” (essentially a music show). Here’s the code I plugged into the Shortcode Widget:


            • dd-term meta returns the Location Link
            • img-term-meta returns the Location Image
            • both are inside the tag to create the link to the Location’s website from its image.

            Very happy with this! I’ve been banging my head against the wall trying to figure out how to display custom fields inside my custom taxonomies! Until now!!!

            I see that you tweaked the code a bit more in your video from what you linked above. I look forward to seeing that and diving in even deeper.

            And finally, I totally agree with a commenter on your YouTube Channel — you deserve far more subscribers! Your stuff is great!

            Cheers!
            Todd

            • Hi Todd,

              Nice! I’ll try looking into incorporating the Google Map custom field.

              I just updated the code for displaying taxonomy images in a loop grid which you can find here – https://daveden.co.uk/tutorials/how-to-add-taxonomy-images-to-elementor-loop-grid/

              Sorry that the code didn’t display properly in the comment. You may have to wrap code in <code></code> if you want it to display properly.

              Please let me know if you figure out how to work with Google Maps Custom Field.

              Thanks for your kind words. I hope to continue creating useful content.

  • Thanks for the video.
    I try to use this snippet php, for a heading element in a single-post page, but it does not work.
    Maybe I need another code?

    • Hi, can you please describe what you did in detail.
      Are you using ACF? Did you create a color metafield for your taxonomy?

      • Hi,
        Exactly what you did.
        I created ACF with the name: “category-color”, for the field of the color of the category. Taxonomy with the name: “project-type”.
        I changed your PHP code to match my names.
        After that, I set a shortcode in Elementor properties.

        This is my code:
        function cat_color_shortcode() {
        global $post;
        $post_id = $post->ID;
        $term_list = wp_get_post_terms($post_id, ‘project-type’, array(‘fields’ => ‘ids’));
        $term_id = (int)$term_list[0];
        $color = get_field(‘category-color’, ‘term_’.$term_id);
        if($color) {
        return $color;
        } else {
        return ”;
        }
        }
        add_shortcode(‘cat-color’, ‘cat_color_shortcode’);

  • Thank you! This was such a life-saver for me today!

  • How did you add the filtering to the loop with a another plugin?

  • How did you add the filtering for the loop , by another plugin or using beta version taxonomy filter?

Leave your comment