Black Friday 50% OFF! Coupon “BLACKFRIDAY50” Ends in:

0

Days

:

0

Hrs

:

0

Mins

:

0

Secs

Shop now!
WPLake > Learning Hub > ACF Taxonomy Field: Complete Guide with Code Snippets

ACF Taxonomy Field: Complete Guide with Code Snippets

Discover the ACF Taxonomy field: Connect, display, and manage taxonomy terms with flexible options and bidirectional updates.

Key Points at a Glance

  1. About the ACF Taxonomy field: Connects posts, pages, or custom post types to taxonomy terms like categories, tags, or custom taxonomies.
  2. Appearance options: Supports checkboxes, multi-select, radio buttons, and dropdowns, each offering different selection capabilities.
  3. Storage format: Stores selected terms as IDs in postmeta or taxonomy tables, depending on settings.
  4. Bidirectional feature: Automatically updates related fields, eliminating the need for manual queries.
  5. Displaying items: The ACF Taxonomy field can display selected terms as lists, hierarchical structures, sliders, or detailed views using frameworks like Advanced Views or custom code, providing flexibility in presentation.

Table of Contents

The ACF Taxonomy field is part of the Relational field group within the Advanced Custom Fields plugin. It allows you to connect posts, pages, or custom post types to taxonomy terms like categories, tags, or custom taxonomies.

This field can function independently or serve as an alternative to the standard WordPress taxonomy selector, offering more flexibility in how you display and manage taxonomy relationships on your site.

Taxonomy field UI

ACF Taxonomy field
The taxonomy field allows editors to choose terms within a single taxonomy.
Editors look of ACF Taxonomy field
The checkbox is the default appearance setting and supports multiple values.
Multiselect appearance of the ACF Taxonomy field
The multi-select is another appearance setting that supports multiple values.
Radio buttons appearance of the ACF taxonomy field
The radio button setting limits the editor's choice to one item.
Select appearance of ACF Taxonomy field
The select setting is another option that limits the editor's choice to one item.

ACF Taxonomy field-related addons

ACF addons can be an important part of the workflow, and there are several addons especially useful for the ACF Taxonomy field:

  • ACF Quick Edit Fields enhances the WordPress admin experience by adding Quick Edit functionality to Advanced Custom Fields. This plugin allows you to quickly view and edit ACF field values directly from the list views.
  • ACF Tooltip enhances the user experience by managing lengthy instruction texts in ACF fields. Instead of cluttering the edit screen, this plugin allows you to add tooltips to field labels, keeping the interface clean and space-efficient.
  • WPGraphQL for ACF allows you to expose ACF fields and field groups to GraphQL, enabling seamless querying of ACF data within your GraphQL queries.

Taxonomy fields in other meta-field plugins

If you're exploring alternatives to ACF, consider that the Taxonomy field in ACF is similar to field types in other plugins. For example, the MB Post field offers comparable functionality, as does the Pods Relationship field.

To gain a deeper understanding of how these options stack up against each other, check out our detailed meta-field plugin comparison. This guide will help you navigate the differences and select the best tool for your needs.

1. ACF Taxonomy field essentials

1.1) Field settings

General tab

  1. Taxonomy filter:
    This setting allows you to choose which taxonomy terms to display in the field. You can't allow mixing different terms within a single field.
  2. Create terms:
    This option lets editors create new taxonomy terms directly from the field interface.
  3. Load terms:
    When enabled, this setting loads and displays the existing terms assigned to the post when editing it. (Refer to the value storage chapter for details)
  4. Save terms:
    If enabled, the selected terms will automatically be saved to the post's terms upon saving the post. (Refer to the value storage chapter for details)
  5. Return value:
    Term Object: Returns the full term object, including all term details like name, slug, and ID.
    Term ID: Returns only the term ID.
  6. Appearance:
    Controls the input appearance.
    Checkbox: Display terms as a checkbox list, allowing users to select multiple options.
    Multi Select: Allows selecting multiple terms using a multi-select dropdown.
    Radio Button: Restricts selection to a single term.
    Select: A dropdown menu for single-term selection.
  7. Allow null
    Allows the field to have no selection, returning a null value if nothing is chosen.

Advanced tab

  1. Bidirectional
    This setting is part of an advanced configuration, often used in conjunction with bidirectional relationships. It allows the taxonomy term to know which posts it is related to, and vice versa, enhancing the management of relationships.

1.2) Storage format

The ACF Taxonomy field always stores the selected terms as IDs. How these values are stored depends on the Save Terms setting:

  • If Save Terms is unchecked:
    The selected term IDs are saved in the postmeta table, just like other custom field data.
  • If Save Terms is checked:
    The term IDs are saved directly in the WordPress core taxonomy tables (term_relationships, term_taxonomy), syncing the field with WordPress's native term assignment system.
Serialized value of the ACF Taxonomy field in the postmeta table
Taxonomy field values in the Postmeta table (default behavior).
WordPress term relationships table
Taxonomy field values in the term_relationships table (if enabled).

The Appearance setting also impacts the storage format:

  • Single Selection:
    When only one term can be selected, the term ID is stored as a numeric string.
  • Multiple Selection:
    If multiple terms are allowed, the IDs are stored as a serialized array of numeric values.

Example of the serialized IDs array:

a:3:{i:0;s:1:"6";i:1;s:2:"15";i:2;s:2:"23";}

This array indicates that three terms are selected, with IDs 6, 15, and 23.

1.3) Supported field locations

You can use the ACF Taxonomy field in various contexts, and it consistently stores the selected term IDs regardless of where you apply the field:

  1. Post Objects (Post, Page, Media Attachment, CPT Item, WooCommerce Product):
    The IDs selected in the ACF Taxonomy field are stored in the wp_postmeta table, associated with the relevant post or custom post type item.
  2. Options page
    The ACF Taxonomy field can be used on an ACF Options Page. In this context, the selected term IDs are stored in the wp_options table. This makes the related content accessible as a global site-wide setting, useful for consistent references across the entire site.
  3. User profiles
    When the Taxonomy field is added to user profiles, the selected term IDs are saved in the wp_usermeta table. This links the related content to the specific user profile, allowing for user-specific content relationships.
  4. Terms (e.g. Post Categories)
    For terms like post categories, tags, or custom taxonomies, the ACF Taxonomy field can be attached, with selected term IDs stored in the wp_termmeta table. This associates the relation with specific terms, enhancing taxonomy-based content organization.
  5. ACF Gutenberg block
    When used within an ACF Gutenberg Block, the Taxonomy field’s selected term IDs are stored within the post_content of the wp_posts table as part of the block’s JSON data structure. This integrates the related content into the block’s content, ensuring that the relationships are preserved within the block.

1.4) Return value formats

The ACF Taxonomy field returns one or multiple items, depending on the 'Multiple' field setting. The format of the item is determined by the Return Value setting, which specifies how the data is returned when using the ACF get_field() function. The available formats are:

  1. Term object
    When this option is selected, each item in the returned array is a WP_Term instance. This provides access to all post properties and methods, allowing you to interact with the terms directly.
  2. Term id
    With this setting, the return value consists of a term ID (or an array of term IDs). Each ID corresponds to a specific term. You can use these IDs with functions like get_term() to retrieve additional information or manipulate the terms as needed.

2. Value storage: Post meta vs. Term tables

The most crucial consideration regarding the Taxonomy field is its storage mechanism. By default, like other field types, the Taxonomy field stores the editor's choice in the Postmeta table.

Serialized value of the ACF Taxonomy field in the postmeta table
By default, taxonomy stores a serialized array of term IDs in the post-meta table

In addition, if the taxonomy field is configured to allow multiple choices, the value will be serialized, which can make querying by it difficult.

So the default Taxonomy field behavior differs from the core WordPress taxonomies feature, which utilizes separate tables. Primarily, this storage method affects the querying process. The post meta table is not optimized for queries, whereas taxonomy tables are.

Custom WordPress Taxonomy
WordPress taxonomies
WordPress term relationships table
Unlike meta fields, WordPress taxonomies utilize separate tables optimized for queries

Therefore, if you intend to query posts by the taxonomy field and have many items in your Custom Post Type (CPT), using the Postmeta storage can significantly degrade performance.

However, this doesn't mean we should automatically prefer the native Taxonomies feature and disregard the Taxonomy field. Fortunately, ACF developers have addressed this issue.

The Taxonomy field offers 'Load' and 'Save' terms options. When enabled, the Taxonomy field starts utilizing the WordPress taxonomy tables while retaining the familiar UI for editors and easy code access for us.

ACF Taxonomy field
Enabling the 'save' and 'load' terms options stores values in WordPress taxonomy tables.

We recommend always enabling these settings. While you may not need to query by that taxonomy field right away, it may be necessary later on. If you haven't enabled them initially, migrating tasks can become a hassle.

Note: If you've added the Taxonomy field to a User or Term location, the 'load' and 'save' term options won't have any effect. This is because WordPress term tables are designed to work exclusively with posts and Custom Post Types. In such cases, the terms are stored in the meta table.

3. Taxonomy bidirectional feature

Considering the storage chapter, you may wonder why to use the Taxonomy field instead of native WP taxonomies. Although both provide the same functionality, just with a different UI, the reason to prefer ACF Taxonomy may not just be UI preferences.

The ACF Taxonomy field supports the bidirectional feature, allowing for the automatic updating of fields on related objects. This feature eliminates the need for making queries altogether and allows us to use the field value instead. It's much easier, especially for beginners.

Bidirectional setting of the ACF Taxonomy field
The bidirectional feature allows us to automatically keep related fields up-to-date.

So how does it work? Suppose we have the Book CPT and Genre Taxonomy. We create a 'genre' taxonomy field and attach it to the Book CPT. Then we create a 'books' relationship field and attach it to the Genre Taxonomy, enabling the bidirectional feature for both, and choosing each other in the settings.

Now the fields are synced, meaning that adding or removing Book CPT items in some Genre taxonomy item will add or remove this taxonomy for the Book CPT terms list.

Isn't it nice? Now we can get a list of Books of the current Genre, or vice versa, without making any queries at all.

Using the bidirectional feature along with the 'load' and 'save' term field settings allows you to create a taxonomy field that's like steroids, making it easier to use than the native WP taxonomies UI.

4. Use cases of the ACF Taxonomy field

Categorization is an essential part of content structuring, and the ACF Taxonomy field offers a powerful way to enhance it. Here are some key use cases that demonstrate its advantages:

4.1) Using Taxonomy field as a dynamic alternative to select fields

The ACF Taxonomy field can serve as a superior alternative to standard Select fields. Unlike the Select field, the Taxonomy field not only allows users to choose existing taxonomy terms but also enables editors to add new terms directly from the interface. This makes it a dynamic tool for managing categories, tags, or any custom taxonomy without switching screens or editing backend settings.

4.2) Replacing native WordPress Taxonomy widget for better UI

The ACF Taxonomy field offers a more user-friendly and visually appealing interface compared to the native WordPress taxonomy widget. With multiple display options like checkboxes, radio buttons, or multi-select, it provides a cleaner and more intuitive experience for editors when selecting terms.

4.3) Streamlining Taxonomy management in custom development

One of the key advantages of using the ACF Taxonomy field is that it provides a unified point for managing taxonomies in code, just like other ACF fields. This consistency simplifies code management, allowing developers to handle taxonomies using familiar ACF functions and hooks.

5. ACF Taxonomy field support in Themes and Builders

ACF is one of the most popular WordPress plugins, and it's supported by many page builders right out of the box. However, most of these integrations are basic, providing limited control over layout or lacking support for advanced field types like Gallery or Repeater.

To achieve universal compatibility with any theme and page builder while gaining advanced control over your layout, consider using the Advanced Views Framework or custom code snippets as discussed in the following chapter.

Here's a snapshot of the built-in features offered by some of the most popular WordPress themes and page builders for displaying ACF Taxonomy fields:

Theme/BuilderACF-related featureACF Taxonomy type support
Astra-no
AvadaDynamic Contentno (not declared)
BeaverACF Moduleyes
BricksDynamic datano (not declared)
DiviACF Moduleyes
ElementorDynamic Tagsno (not declared)
GeneratePress-no
Gutenberg-no
KadenceDynamic Contentno (not declared)
OceanWP-no
Visual ComposerDynamic Contentno (not declared)
WPBackery-no

While this list may seem brief, many themes come with their own page builders. Check your theme’s documentation for guidance on displaying ACF Taxonomy fields, or refer to the universal methods outlined below for a more flexible approach.

6. Code snippets for the ACF Taxonomy field

ACF functions and their responses are essentially wrappers around built-in WordPress features. This means that to load and display field values, you need to be familiar not only with ACF but also with core WordPress classes and functions. Additionally, writing markup from scratch and manually escaping data can be time-consuming.

To streamline development, you can use the Advanced Views Framework. This WordPress framework offers smart templates for the front end, simplifying post queries and template creation. It generates default markup and automatically loads the escaped data into the template, allowing you to focus on the layout itself.

Unlike drag-and-drop page builders, smart templates in Advanced Views are modular and based on a template engine (Twig or Blade), providing full control over the markup and helping you avoid the pitfalls of global CSS and JavaScript files. The framework natively supports all ACF field types, along with other data sources.

Below are examples for both Advanced Views and custom code:

6.1) Loading and displaying items

The simplest way to display the chosen items is to turn them into a list of clickable titles.

Courses taxonomy items
Example of a list for the custom "Courses" term items.

Using Advanced Views Framework

  1. Navigate to the Views section and create a new View.
  2. Select the Taxonomy field in the Fields tab.
  3. Save the View; a template will be automatically generated. You can copy and modify this template as needed.
  4. To integrate it into your page, paste the generated shortcode or use the Custom Gutenberg block option.

The default template presents items as links, so you can leave it as is. When the multiple-value appearance is chosen, it'll look like this:

{% if taxonomy_multiple.value %}
    <div>
        {% for term_item in taxonomy_multiple.value %}
            <a target="{{ term_item.target }}" href="{{ term_item.value }}">
                {{ term_item.linkLabel|default(term_item.title) }}
            </a>
        {% endfor %}
    </div>
{% endif %}

When the single-value appearance, it will have a single link only:

{% if taxonomy.value %}
    <a target="{{ taxonomy.target }}" href="{{ taxonomy.value }}">
        {{ taxonomy.linkLabel|default(taxonomy.title) }}
    </a>
{% endif %}

Visit the page to see the result. If it needs, you can add CSS rules to the CSS field of your View, to get the desired look.

Loading from different locations: To load a field from different locations (e.g., user profile), use the object-id shortcode argument.

Using custom code

To load the field value, you should use the ACF get_field function. Its response will differ based on the 'Appearance' option and the chosen return format. By default, only the 'Checkbox' appearance is chosen, and the return format is Term Object.

In case you've changed it to Term ID, you'll need to use the get_post() function to get the Term Instance. To get the term link, use the get_term_link() function.

By default, the get_field() function loads the value from the current object (page/post). In case you need to load from the other source, pass it as a second argument. Don't forget about security and escape the output, as shown below.

For the multiple-value appearance use the following code:

// Replace 'taxonomy_field' with the name of your ACF Taxonomy field
$selected_terms = get_field('taxonomy_field'); // from the current post
$selected_terms = get_field('taxonomy_field', 10); // from a specific post by ID
$selected_terms = get_field('taxonomy_field', 'option'); // from the options page
$selected_terms = get_field('taxonomy_field', 'user_1'); // from the user by ID
$selected_terms = get_field('taxonomy_field', 'category_2'); // from the category term with ID 2
$selected_terms = get_field('taxonomy_field', 'genre_3'); // from the custom genre term with ID 3

if ($selected_terms) {
    printf('<div class="taxonomy-terms">');
    foreach ($selected_terms as $selected_term) {
        // Uncomment the line below if the return format is set to Term ID
        // $selected_term = get_term($selected_term);

        // Display term name as a link to the term archive
        printf(
            '<a class="taxonomy-term__item" href="%s">%s</a>',
            esc_url(get_term_link($selected_term)),
            esc_html($selected_term->name)
        );
    }
    printf('</div>');
}

For the single-value appearance:

// Replace 'taxonomy_field' with the name of your ACF Taxonomy field
$selected_term = get_field('taxonomy_field'); // from the current post
$selected_term = get_field('taxonomy_field', 10); // from a specific post by ID
$selected_term = get_field('taxonomy_field', 'option'); // from the options page
$selected_term = get_field('taxonomy_field', 'user_1'); // from the user by ID
$selected_term = get_field('taxonomy_field', 'category_2'); // from the category term with ID 2
$selected_term = get_field('taxonomy_field', 'genre_3'); // from the custom genre term with ID 3

if ($selected_term) {
    // Uncomment the line below if the return format is set to Term ID
    // $selected_term = get_term($selected_term);
    
    // Display term name as a link to the term archive
    printf(
        '<a class="taxonomy-term__item" href="%s">%s</a>',
        esc_url(get_term_link($selected_term)),
        esc_html($selected_term->name)
    );
}

To style the items in the ACF Taxonomy field, you can add CSS rules to your theme's style.css file. However, keep in mind that this will enqueue the styles sitewide. A better approach is to add the CSS to the specific template assets or use the modular Advanced Views.

6.2) Displaying items hierarchically

WordPress taxonomies support a hierarchical structure, allowing you to create parent-child relationships between items. For example, you can have terms like "USA" as the parent and cities like "New York" and "Los Angeles" as children.

Editors look of ACF Taxonomy field
When a taxonomy supports hierarchy, ACF handles it seamlessly right out of the box.

While WordPress and ACF handle this hierarchy properly in the backend, the terms are returned in a linear fashion on the front end, requiring manual grouping to maintain the correct display order.

Using Advanced Views Framework

In case you're using AVF, your task consists only of updating the template, to incorporate grouping, as shown in the AVF Taxonomy Docs:

{% if taxonomy_multiple.value %}
    <div>
        <!-- Loop through terms to identify and display top-level (parent) terms -->
        {% for term_item in taxonomy_multiple.value %}
            {% if 0 == term_item.parent_id %}
                <!-- Display the parent term -->
                <a class="top-item" target="{{ term_item.target }}" href="{{ term_item.value }}">
                    {{ term_item.linkLabel|default(term_item.title) }}
                </a>

                {% set children = [] %}

                <!-- Loop again to find child terms of the current parent term -->
                {% for inner_term_item in taxonomy_multiple.value %}
                    {% if term_item.value == inner_term_item.parent_id %}
                        {% set children = children|merge([inner_term_item]) %}
                    {% endif %}
                {% endfor %}

                <!-- If there are child terms, display them under their parent -->
                {% if children %}
                    <div class="children">
                        {% for child_term_item in children %}
                            <a class="child-item" target="{{ child_term_item.target }}" href="{{ child_term_item.value }}">
                                {{ child_term_item.linkLabel|default(child_term_item.title) }}
                            </a>
                        {% endfor %}
                    </div>
                {% endif %}
            {% endif %}
        {% endfor %}
    </div>
{% endif %}

All the items, including the parent_id property, are loaded by the framework automatically. Now you can style items using the assigned top-item and child-item classes.

Using custom code

To group the items, you need to use the parent property of the WP_Term instance, and to get the term link, use the get_term_link() function as shown below. Don't forget about security and escape the output:

// Replace 'taxonomy_field' with the name of your ACF Taxonomy field
$selected_terms = get_field('taxonomy_field'); // from the current post

if ($selected_terms) {
    // Convert term IDs to term objects if needed
    $selected_terms = array_map(function ($term) {
        return is_numeric($term) ? get_term($term) : $term;
    }, $selected_terms);

    // Group terms by parent ID
    $terms_by_parent = [];
    foreach ($selected_terms as $term) {
        $terms_by_parent[$term->parent][] = $term;
    }

    // Display top-level terms (terms with no parent)
    if (!empty($terms_by_parent[0])) {
        printf('<div class="taxonomy-terms">');
        foreach ($terms_by_parent[0] as $parent_term) {
            // Display parent term
            printf(
                '<a class="top-item" href="%s">%s</a>',
                esc_url(get_term_link($parent_term)),
                esc_html($parent_term->name)
            );

            // Check and display child terms if they exist
            if (!empty($terms_by_parent[$parent_term->term_id])) {
                printf('<div class="children">');
                foreach ($terms_by_parent[$parent_term->term_id] as $child_term) {
                    printf(
                        '<a class="child-item" href="%s">%s</a>',
                        esc_url(get_term_link($child_term)),
                        esc_html($child_term->name)
                    );
                }
                printf('</div>'); // End children
            }
        }
        printf('</div>'); // End taxonomy-terms
    }
}

Now you can style items using the assigned top-item and child-item classes.

6.3) Displaying detailed term info

When working with taxonomy terms, you often need to display more than just the term name. Whether it’s built-in WordPress fields like descriptions or custom ACF fields, you can enhance your term output with additional details.

Detailed WP term info
Example of the detailed WP term display: name (wp), description(wp), estimated workload (ACF), and image (ACF).

Using Advanced Views Framework

To display term details, follow the steps, described in the AVF Taxonomy field Docs:

  1. Use the AVF Pro Edition: Ensure you have the AVF Pro edition, which allows you to customize the appearance of object fields.
  2. Create the Primary View: Start by creating the main View, which will act as the master View. Choose the target taxonomy field as save the View.
  3. Create a ‘Term Details’ View: This View will be responsible for displaying term details.In the Fields tab, select the term fields you want to display, such as the description and image (an ACF Image field).
  4. Save the 'Term Details' View: After setting up the fields, save the 'Term Details' View.
  5. Link the Views: Go back to the primary (master) View. In the Taxonomy field settings, select the 'Term Details' View in the 'View' setting.
  6. Save the Master View: Save the master View to complete the setup.
  7. Customize as Needed: Now, each chosen term in the Taxonomy field will be displayed according to the 'Term Details' View. You can further customize the markup and add CSS styles as needed.

That's it! By following these steps, you can display detailed term information and have full control over the layout and styling.

If you've multiple items, to display all of them in a single row, you can use the CSS Flexbox:

#view__terms {
display: flex;
gap: 10px;
}

To display all the items as a grid, you can use the CSS Grid:

#view__terms {
 display: grid;
 grid-template-columns: 1fr;
 gap: 20px;
 }

@media screen and (min-width:992px) {
 #view__terms {
  grid-template-columns: repeat(4, 1fr);
 }
}

Using custom code

In this example, we use the get_term_link() function to fetch the term page link, and wp_get_attachment_image() function to get the proper image tag with attributes for the attached ACF Image field.

For loading the ACF fields from the term, we should use the {taxonomy-name}_{term_id} source format. The code includes a loop to handle multiple terms; if you're working with a single-term response, simply remove the loop and adjust the variables accordingly. Don't forget about security, and escape the output data as shown below:

// Replace 'taxonomy_field' with the name of your ACF Taxonomy field
$selected_terms = get_field( 'taxonomy_field' ); // Adjust context as needed (post, options, user, etc.)

if ( $selected_terms ) {
	echo '<div class="terms">';
	foreach ( $selected_terms as $selected_term ) {
		// Uncomment the line below if the return format is set to Term ID
		 $selected_term = get_term($selected_term);

		echo '<div class="term">';

		// Display term name as a link to the term archive
		printf(
			'<a class="taxonomy-term__item" href="%s">%s</a>',
			esc_url( get_term_link( $selected_term ) ),
			esc_html( $selected_term->name )
		);

		// Display term description
		if ( ! empty( $selected_term->description ) ) {
			printf(
				'<p class="taxonomy-term__description">%s</p>',
				esc_html( $selected_term->description )
			);
		}

		// todo replace "genre" with the name of your taxonomy
		$time_to_learn = get_field( 'time_to_learn', 'genre_' . $selected_term->term_id );
		if ( $time_to_learn ) {
			printf(
				'<p class="taxonomy-term__time-to-learn">Time to Learn: %s</p>',
				esc_html( $time_to_learn )
			);
		}

		// todo replace "genre" with the name of your taxonomy
		$term_image = get_field( 'acf_image_field', 'genre_' . $selected_term->term_id );
		if ( $term_image ) {
			echo wp_get_attachment_image( $term_image['ID'], 'full', false, [
				'class' => 'taxonomy-term__image',
				'alt'   => esc_attr( $term_image['alt'] ?? $selected_term->name ),
			] );
		}

		echo '</div>'; // closing item div
	}

	echo '</div>'; // closing items div
}

To display all the items in a single row, you can use the CSS Flexbox:

.terms {
display: flex;
gap: 10px;
}

To display all the items as a grid, you can use the CSS Grid:

.terms {
 display: grid;
 grid-template-columns: 1fr;
 gap: 20px;
 }

@media screen and (min-width:992px) {
 .terms {
  grid-template-columns: repeat(4, 1fr);
 }
}

6.4) Displaying terms in a slider

Another great way to showcase the terms is to display them in a slider. We can display one item at a time, or opt for multiple at once, as well as enable the auto slide option.

Splide slider
The horizontal slider allows you to showcase one or multiple items at a time and smoothly scroll to the next set of items.

The first thing to do is to select the target slider library. In this article, we've opted for Splide, which is a well-known library with rich options and excellent performance.

The simplest way to turn the repeater into the slider is to use AVF Pro edition, as the framework comes with pre-configured Slider, Masonry, and Image gallery libraries.

Using Advanced Views Framework

After adding the Taxonomy field configured to the 'multiple' appearance to the target View, change the 'Enable Slider' option to 'Splide v4' and press the Save button, as described on the AVF Taxonomy Docs page. The framework will automatically change the field markup to incorporate the necessary classes, and add the default JS instance:

var term_items = this.querySelector('.acf-view__terms');
if (term_items) {
	/* https://splidejs.com/guides/options/ */
	new Splide(term_items, {
		type: 'loop',
		perPage: 1,
		perMove: 1,
	}).mount();
}

Now you can customize the settings according to your needs, using any available Splide options.

Using custom code

In this case, you need to download the CSS and JS code of the Splide library to your theme. Then, print the term items in the target template with the necessary splide classes:

// Replace 'taxonomy_field' with the name of your ACF Taxonomy field
$selected_terms = get_field('taxonomy_field'); // Adjust context as needed (post, options, user, etc.)

if ($selected_terms) {
    echo '<div class="splide">'; // Splide container
    echo '<div class="splide__track">'; // Splide track
    echo '<ul class="splide__list terms">'; // Splide list

    foreach ($selected_terms as $selected_term) {
        // Uncomment the line below if the return format is set to Term ID
        $selected_term = get_term($selected_term);

        echo '<li class="splide__slide term">'; // Splide slide item

        // Display term name as a link to the term archive
        printf(
            '<a class="taxonomy-term__item" href="%s">%s</a>',
            esc_url(get_term_link($selected_term)),
            esc_html($selected_term->name)
        );

        // Display term description
        if (!empty($selected_term->description)) {
            printf(
                '<p class="taxonomy-term__description">%s</p>',
                esc_html($selected_term->description)
            );
        }

        // Replace "genre" with the name of your taxonomy
        $time_to_learn = get_field('time_to_learn', 'genre_' . $selected_term->term_id);
        if ($time_to_learn) {
            printf(
                '<p class="taxonomy-term__time-to-learn">Time to Learn: %s</p>',
                esc_html($time_to_learn)
            );
        }

        // Replace "genre" with the name of your taxonomy
        $term_image = get_field('acf_image_field', 'genre_' . $selected_term->term_id);
        if ($term_image) {
            echo wp_get_attachment_image($term_image['ID'], 'full', false, [
                'class' => 'taxonomy-term__image',
                'alt'   => esc_attr($term_image['alt'] ?? $selected_term->name),
            ]);
        }

        echo '</li>'; // Closing slide item
    }

    echo '</ul>'; // Closing Splide list
    echo '</div>'; // Closing Splide track
    echo '</div>'; // Closing Splide container
}

Then enqueue the library's CSS using the wp_enqueue_style function, and add the following JS to your theme's script.js:

import '/wp-content/themes/YOUR_THEME/assets/js/splide.js';

document.addEventListener('DOMContentLoaded', function () {
    var slider = document.body.querySelector('.splide');
    if (slider) {
        /* https://splidejs.com/guides/options/ */
        new Splide(slider, {
            type: 'loop',
            perPage: 1,
            perMove: 1,
        }).mount();
    }
});

Now you can customize the settings according to your needs, using any available Splide options.

6.5) Updating the Taxonomy field programmatically

To update the Taxonomy field programmatically, you can use the ACF update_field function. Since this field stores the term ID, the data you pass must be either a term ID or an array of term IDs, depending on the Appearance setting of the field.

add_action( 'acf/init', function () {
	// 1. For fields without the multiple option (single term selection)
	// Replace 'my_taxonomy_field' with your field name, 10 with your chosen term ID,
	// and 1 with the source post ID (where the value will be updated)
	update_field( 'my_taxonomy_field', 10, 1 );

	// 2. For fields with the multiple option (multiple term selection)
	// Replace 'my_taxonomy_field' with your field name, 10 and 20 with your chosen term IDs,
	// and 1 with the source post ID (where the value will be updated)
	update_field( 'my_taxonomy_field', [ 10, 20 ], 1 );
} );

If you need to update the Taxonomy field on a user or term object, you must add the appropriate prefix, just as shown in the "loading" field value section.

Note: You should call the update_field function inside the acf/init action, or in any hooks that happen later.

7. Quering by the ACF Taxonomy field

Querying the ACF Taxonomy field depends on how the values are stored. As mentioned earlier, if the 'load' and 'save' terms options are active, ACF will use the built-in Term tables, which are highly efficient for any query volumes, including large datasets.

Additionally, you won't need to use the 'LIKE' comparison trick, commonly required otherwise, e.g. in the case with the ACF Relationship field.

Note: If you've added the Taxonomy field to a User or Term location, the 'load' and 'save' term options won't have any effect. This is because WordPress term tables are designed to work exclusively with posts and Custom Post Types. In such cases, the terms are stored in the meta table, requiring you to use standard meta queries when retrieving them.

7.1) By postmeta (Post, Page, Any CPT)

Using Advanced Views Framework:

If you're using the AVF: Pro edition, querying by ACF Taxonomy field values is straightforward with Taxonomy Filters. You need to create a Card, choose the target Taxonomy in the Taxomies tab, and define the desired value. It can be a static term or pointer to another field.

Save, and copy the Card's shortcode and paste to the target place. That's it - the framework will take care of the rest.

Using custom code:

To query posts by specific taxonomy term, you need to employ the WP_Query class:

// Query posts by terms using WP_Query
$args = array(
    'post_type' => 'post', // Replace with your custom post type if needed
    'post_status' => 'publish',
    'posts_per_page' => -1, // Retrieve all posts
    'tax_query' => array(
        array(
            'taxonomy' => 'category', // Replace with your taxonomy
            'field'    => 'term_id',  // Use term ID to match saved value
            'terms'    => 10,         // Replace with your term ID
        )
    )
);

// Execute the query
$query = new WP_Query($args);

// Loop through the results
foreach ($query->get_posts() as $post) {
    // Process each WP_Post object here
    // For example, display the post title
    echo '<h2>' . get_the_title($post->ID) . '</h2>';
}

7.2) By termmeta (Terms)

Here we need to employ the WP_Term_Query class.

For fields with the 'multiple' appearance:

$args = array(
    'taxonomy'   => 'category', // Replace with your taxonomy
    'meta_query' => array(
        array(
            'key'     => 'your_taxonomy_field', // Replace with your ACF Taxonomy field key
            'value'   => '"10"', // Target term ID wrapped in double quotes to match serialized data
            'compare' => 'LIKE',
        )
    )
);

// Execute the query
$term_query = new WP_Term_Query($args);

// Loop through the results
foreach ($term_query->get_terms() as $term) {
    // Process each WP_Term object
    // Example: echo $term->name;
}

For fields without the 'multiple' appearance:

$args = array(
    'taxonomy'   => 'category', // Replace with your taxonomy
    'meta_query' => array(
        array(
            'key'     => 'your_taxonomy_field', // Replace with your ACF Taxonomy field key
            'value'   => '10', // Target term ID
        )
    )
);

// Execute the query
$term_query = new WP_Term_Query($args);

// Loop through the results
foreach ($term_query->get_terms() as $term) {
    // Process each WP_Term object
    // Example: echo $term->name;
}

7.3) By usermeta (user profile)

In this case, we need to use the WP_User_Query class.

For fields with the 'multiple' appearance:

$args = array(
    'meta_query' => array(
        array(
            'key'     => 'your_taxonomy_field', // Replace with your ACF Taxonomy field key
            'value'   => '"10"', // Target term ID wrapped in double quotes to match serialized data
            'compare' => 'LIKE',
        )
    )
);

$user_query = new WP_User_Query($args);

// Loop through the results
foreach ($user_query->get_results() as $user) {
    // Process each WP_User object
    // Example: echo $user->user_login;
}

For fields without the 'multiple' appearance:

$args = array(
    'meta_query' => array(
        array(
            'key'     => 'your_taxonomy_field', // Replace with your ACF Taxonomy field key
            'value'   => '10', // Target term ID
        )
    )
);

$user_query = new WP_User_Query($args);

// Loop through the results
foreach ($user_query->get_results() as $user) {
    // Process each WP_User object
    // Example: echo $user->user_login;
}

7.4) Inside ACF Blocks

ACF Blocks save their data as JSON in the post_content. This data cannot be queried directly. However, if you enable the "Save in Meta" feature for ACF Blocks, the field values are also saved in post meta, allowing you to query them similarly to other postmeta fields.

8. Related Taxonomy field filters and hooks

ACF offers a variety of filters and hooks that enable you to modify field data and behavior, extending WordPress's core hooks functionality. You can utilize the standard add_action and add_filter functions to attach custom code to these hooks.

Below are some of the most commonly used hooks along with the ACF Taxonomy field type:

8.1) acf/fields/taxonomy/result

Using the acf/fields/taxonomy/result filter, you can modify the display of taxonomy terms in the field’s dropdown list. By default, it shows term names, but you can enhance it, for example, by appending term IDs:

add_filter( 'acf/fields/taxonomy/result', function ( string $title, \WP_Term $term, array $field, int $post_id ): string {
    $title .= ' [' . $term->term_id . ']';

    return $title;
}, 10, 4 );

Note: This filter only modifies how terms are presented in the field dropdown; it doesn't affect the field’s search algorithm. For search modifications, refer to the query filter described below.

8.2) acf/fields/taxonomy/query and acf/fields/taxonomy/wp_list_categories

The acf/fields/taxonomy/query and acf/fields/taxonomy/wp_list_categories filters let you customize the search logic of the Taxonomy field.

Note: You should use the query filter in case your field is configured for Select and Multi Select appearance, and the wp_list_categories filter otherwise.

The query filter is based on WP_Term_Query, allowing you to tweak its parameters:

add_filter( 'acf/fields/taxonomy/query', function ( array $args, array $field, int $post_id ): array {
    // Example: Restrict results to terms under a specific parent term
    $args['parent'] = 10; // Replace 10 with the parent term ID

    return $args;
}, 10, 3 );

The wp_list_categories filter is based on the wp_list_categories() function, allowing you to tweak its parameters:

add_filter( 'acf/fields/taxonomy/wp_list_categories', function ( array $args, array $field ): array {
	// Order by most used.
	$args['orderby'] = 'count';
	$args['order']   = 'DESC';

	return $args;
}, 10, 2 );

8.3) acf/load_field

The acf/load_field filter allows you to modify the field settings before it is displayed on the editor's screen. This filter is particularly useful for dynamically adjusting the field's configuration, such as setting default values, changing labels, or customizing available options.

add_filter('acf/load_field/name=my_taxonomy_field', function (array $field): array {
    // Modify the field settings as needed
    $field['instructions'] = 'Please select related terms.';
    $field['taxonomy'] = ['category', 'post_tag']; // Limit to specific taxonomies

    return $field;
});

8.4) acf/render_field

The acf/render_field action allows you to add custom HTML before or after a field's input on the editor's screen in the WordPress admin. This can be particularly useful for adding custom-styled text, icons, styles, or additional interactive elements to enhance the field's functionality.

add_action('acf/render_field/key=field_123456789abc', function (array $field): void {
    // Your custom HTML
    echo '<div class="my-custom-class">Custom taxonomy-related element</div>';
});

Note: By default, the acf/render_field action is triggered after the field input has been printed. If you need to print your HTML before the input, you should set the priority number to 9 or lower in the third argument of the add_action WordPress function.

8.5) acf/validate_value

Use the acf/validate_value filter to validate the values entered into the field. You can ensure that the entered value meets specific criteria:

add_filter('acf/validate_value/name=my_taxonomy_field', function($valid, $value, array $field) {
    if (true !== $valid) {
        return $valid; // Skip validation if there is an existing error
    }

    // Custom validation: Ensure that at least one term is selected
    if (empty($value)) {
        return 'Please select at least one term.';
    }

    return $valid;
}, 10, 3);

8.6) acf/validate_save_post

The acf/validate_save_post action allows you to perform custom form validations before saving ACF fields. This is particularly useful when you need to validate one field's value based on another field's input or enforce specific rules across multiple fields.

add_action('acf/validate_save_post', function () {
    // Get the taxonomy field values from ACF fields
    $taxonomy_field_1 = $_POST['acf']['field_taxonomy_key_1'] ?? '';
    $taxonomy_field_2 = $_POST['acf']['field_taxonomy_key_2'] ?? '';

    if (empty($taxonomy_field_1) && empty($taxonomy_field_2)) {
        acf_add_validation_error('field_taxonomy_key_1', 'At least one taxonomy field must be defined.');
        acf_add_validation_error('field_taxonomy_key_2', 'At least one taxonomy field must be defined.');
    }
});

Tip: To find the field key, navigate to the ACF field group in the WordPress admin. Click on the Screen Options button at the top right corner of the page, then check the Field Keys option. Once enabled, the field keys will be displayed next to each field name in the group.

8.7) acf/save_post

The acf/save_post action is triggered when the current item (page/product/user) is saved. You can use it to perform any additional actions, e.g. updating related data.

add_action('acf/save_post', function ($post_id) {
    // Retrieve the taxonomy field value (replace with your actual taxonomy field key)
    $related_terms = get_field('related_terms', $post_id);

    if (!$related_terms) {
        return;
    }

    // Loop through each related term and update a connected field
    foreach ($related_terms as $term_id) {
        update_field('related_item', $post_id, 'term_' . $term_id); // Replace 'related_item' with your actual field key
    }
});

Stuck with development or facing an issue?

WPLake offers affordable on-demand website development and design.

No matter the size of your project - contact us now, and we'll get it done for you!

Get assistance now

FAQ mode

/

Learning mode

  1. Do "Taxonomy field" and "term fields" mean different things?

    Yes, they do. Although they sound alike, they represent different concepts. The ACF Taxonomy field is a specific field type in Advanced Custom Fields that allows you to select terms (categories, tags, or custom taxonomies) from your WordPress site. In contrast, "term fields" generally refer to the custom fields you add to a specific term using ACF, enhancing term data with additional content like images, descriptions, or other custom data.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

Course navigation: ACF Plugin

Content links (96)

About the Author

Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly


    Got it