12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Feb 18, 2022

ACF Taxonomy Term Image in Oxygen

Sridhar Katakam

One use-case of Advanced Custom Fields plugin is being able to set up a custom image field for taxonomy terms (like categories).

This tutorial provides the steps to register a term_image custom field using ACF and adding a custom function that returns the URL of this field’s value for use on the taxonomy term archive pages in Oxygen, thanks to Oxygen’s amazing dynamic data feature.

We shall ensure that a fallback image is shown in case ACF is not active or if the field is not populated for a given term.

Step 1

Install and activate ACF.

Create a field group to be linked to your desired taxonomy.

Add an Image-type of field.

Ex.:

In the above FAQ Category is the taxonomy associated with FAQ Custom Post Type.

Step 2

Edit your taxonomies and select/upload the term image for each.

Step 3

Install and activate Code Snippets plugin.

Go to Snippets > Add New.

Title: [Function] Get ACF Taxonomy Term Image URL

Code:

function wpdd_get_tax_term_image_url( $image_field ) {
	if ( class_exists( 'ACF' ) && get_field( $image_field, get_queried_object() ) ) {
		$term_image = get_field( $image_field, get_queried_object() );
		
		$term_image_url = esc_url( $term_image['url'] );
	} else {
		$term_image_url = '/wp-content/uploads/2022/02/default-term-image.jpg';
	}

	return $term_image_url;
}

In the above replace

/wp-content/uploads/2022/02/default-term-image.jpg

with the URL of your fallback image.

Set the snippet to run only on the front-end. Save changes and activate.

Step 4

Edit (or create if not existing) a Template that applies to all your taxonomy terms with Oxygen.

We are now ready to pull the URL of our term’s image custom field value either as the source URL of an Image component or as the URL of a Section’s background image.

Click on data > PHP Function Return value and for the Function Name: wpdd_get_tax_term_image_url

Function Arguments:
term_image

Click INSERT.

That’s it!

Visit any term archive on the front end and you should see the term image.

References

https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/#displaying-fields

https://www.advancedcustomfields.com/resources/image/

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-ocalendar-check-omagnifiercrossmenuchevron-downarrow-right