Rocket Squirrel Rocket Squirrel
Rocket Squirrel

A global community of coders, developers, and designers

March 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031

Categories


Simple way to get a single post’s taxonomy

Get to know the get_the_terms() function

Darren PinderDarren Pinder

So you’ve got a custom taxonomy, and you want to return the taxonomy’s name(s) (“terms”) on a single post template on the front-end.

For example, we have a post type called Careers. Each individual post has a taxonomy called Location (with the slug ‘location’). This taxonomy has multiple terms (in the form of a checkbox list which supports multiple selections).

Try this:


// Get all the current post's terms from the taxonomy taxonomy_name. This can be multiple terms.
$terms = get_the_terms( get_the_ID(), 'taxonomy_name' );

	// If terms were found
	if ( $terms ) :

		// Create an empty array to be filled
		$locations = array();

		// Loop each of the terms found within the $terms array
		foreach ( $terms as $term ) {

			// Add the term name to the $locations array
			$locations[] = $term->name;

		}

		// Join all the array items into a string using join()
		$output_locations = join( ", ", $locations );

	endif;

Owner of Vatu Ltd and Raccoon Events. Organiser at WordCamp London. Into space, code, and running.

Comments 0
There are currently no comments.