Get values from a taxonomy term

Overview

All the template functions can be used to load values from a taxonomy term, however, a second parameter is required to target the term. This is similar to passing through a $post_id parameter to target a specific post object.

There are 3 different styles of $post_id available and are listed below.

Example Format Description
'category_123' $taxonomy . '_' . $term_id A string containing the taxonomy name and term ID
'term_123' 'term_' . $term_id A string containing the word ‘term’ and term ID. Added in version 5.5.0
WP_Term A term object. You can get a term object via many of WP’s functions such as get_term()

Examples

The following examples show a number of ways to interact with term meta.

Display a field

<p><?php the_field('field_name', $term); ?></p>
<p><?php the_field('field_name', 'category_7'); ?></p>

Retrieve a field

<?php

$variable = get_field('field_name', 'product-cat_23');

// do something with $variable

?>

Display a sub field

Note that when inside of a have_rows loop, you do not need to use the $post_id parameter for any sub field functions (get_sub_field, the_sub_field)

<?php if( have_rows('repeater', 'post_tag_2') ): ?>

	<ul>

	<?php while( have_rows('repeater', 'post_tag_2') ): the_row(); ?>

		<li><?php the_sub_field('title'); ?></li>

	<?php endwhile; ?>

	</ul>

<?php endif; ?>

 Finding the term related to the current post

<?php

// load all 'category' terms for the post
$terms = get_the_terms( get_the_ID(), 'category');


// we will use the first term to load ACF data from
if( !empty($terms) ) {
	
	$term = array_pop($terms);

	$custom_field = get_field('category_image', $term );

	// do something with $custom_field
}

?>

Finding the active taxonomy & term on an archive page

<?php 

// vars
$queried_object = get_queried_object(); 
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;  

// load thumbnail for this taxonomy term (term object)
$thumbnail = get_field('thumbnail', $queried_object);

// load thumbnail for this taxonomy term (term string)
$thumbnail = get_field('thumbnail', $taxonomy . '_' . $term_id);
?>

Limitations

auto-embed

When editing a WYSIWYG field on a taxonomy term, the auto-embed functionality may not work. This is due to code within the WordPress core which limits the auto-embed functionality to posts only.

This issue carries onto the front end and prevents embed urls (youtube, vimeo, etc) from being converted to play-able embed objects.

As a current workaround for the front end, use this code at the top of your template (most likely category.php or similar). This code will set a custom post_ID and allow WP to load the embed.

category.php

<?php 

// vars
$queried_object = get_queried_object(); 
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;  

$GLOBALS['wp_embed']->post_ID = $taxonomy . '_' . $term_id;

?>

 

 

Related