Rocket Squirrel Rocket Squirrel
Rocket Squirrel

A global community of coders, developers, and designers

November 2018
M T W T F S S
« Jul    
 1234
567891011
12131415161718
19202122232425
2627282930  

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.