When to / not to use wp_get_post_terms vs get_the_terms?

A user contributed a note in the codex saying the only difference is that get_the_terms use cached data

Yes, get_the_terms relies on the object cache. This gives a scaling boost and a speed boost. If you have an object cache enabled this boost increases speed dramatically.

and I already know that wp_get_post_terms let you retrieve data by slug

I think you mean it lets you return an array of a specific field. A term slug is not a parameter to either function

It’s nothing that cannot be accomplished via wp_list_pluck as term objects contain the slug

but I still wonder what is the best situation to use one vs the other

Just use get_the_terms and pretend that the higher level helper functions don’t exist, they’re more trouble than they’re worth

It falls into the same category of problematic functions as get_children or wp_get_recent_posts, that wrap around lower level functions that do similar things, but try to do a little work for you. Useful for beginners, until you realise that they come with strings that aren’t great or cause problems. Additionally, why learn all those functions when you can just go 1 step down and learn the handful of functions they’re built from and save time and hassle.

The same is true of taxonomies. There’s no need to use category and tag APIs, or taxonomy APIs that refer to posts. Just use the generic versions and specify the taxonomy name, e.g.

$terms = get_the_terms( $post_id, 'cat' );

Now there is a temptation here to go down again to wp_get_object_terms but this is uncached, and so you’ll see performance and scaling issues.

Leave a Comment