4

A user contributed a note in the codex saying the only difference is that get_the_terms use cached data, and I already know that wp_get_post_terms let you retrieve data by slug, but I still wonder what is the best situation to use one vs the other.

10

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.

  • My confusion started because Query Monitor was informing me about duplicate queries. Coincidentally all were due to the use of wp_get_post_terms. I made the transition to get_the_terms in all cases where I used wp_get_post_terms and I no longer have QM notifications. You are correct about the helpers, a year ago they came in handy when my knowledge of php objects and Wordpress plugin development was minimal compared to now, but once you start to develop more robust stuff these helpers become more of an obstacle to scalability. – Luis Rivera Sep 2 '18 at 0:15
  • If the answer satisfies your curiosity, you can always mark it as the correct answer :p – Tom J Nowell Sep 2 '18 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.