Skip to content

Instantly share code, notes, and snippets.

@rosschapman
Created April 2, 2012 22:15
Show Gist options
  • Save rosschapman/2287584 to your computer and use it in GitHub Desktop.
Save rosschapman/2287584 to your computer and use it in GitHub Desktop.
Way to get last term of get_terms array in #wordpress
$terms = get_the_terms($post->ID, $taxonomy);
end($terms);
$term_id = key($terms);
$term = get_term($term_id,$taxonomy);
echo $term->name;
@bobbingwide
Copy link

For WordPress 4.7.3 get_the_terms() returns an array of WP_Term objects.

/**
 * Gets the last term for post's hierarchical taxonomy 
 * 
 * @param object $post
 * @param string $taxonomy 
 * @return integer|null the taxonomy ID
 */
function get_last_term( $post, $taxonomy = "compatible_up_to" ) {
	$terms = get_the_terms($post->ID, $taxonomy);
	if ( $terms ) {
		end( $terms );
		$term = current( $terms );
		//print_r( $term );
		$term_id = $term->term_id;
		echo $term->name;
	} else {
		$term_id = null;
	}	
	return $term_id;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment