WordPress built-in method to extract array of term IDs?

I’m querying a custom taxonomy for a post, hoping to get a list of all terms for that post and taxonomy. get_the_terms($post_id, $taxonomy) works, but gives this ungodly array of term objects that will require an extra layer of parsing before I can run the following code:

if (in_array($list_of_term_ids, $my_term_id)){ do good stuff... }

I’m looking to see whether anyone has come across a native WP function or method that extracts term ids into a flat list before rolling my own utility function, just so I can be using built-in best practices.

2 Answers
2

I know you’ve long since solved this, but wanted to offer another solution. This question popped up as “related” when I was answering another one.

You can use the WordPress function wp_list_pluck to return an array with values as one of the fields of the array or objects sent to the function. In other words, send the function the objects and specify the field you want back and you’ll get an array with only that field.

For instance, you can do something like:

$ids = wp_list_pluck(get_terms('category', 'hide_empty=0'), 'term_id'));

$ids will be an array of the terms ids that you wanted to capture.

Leave a Comment