Check if term object is in array

I want to check if a term object is in an get_terms array, but i really can’t figure out how to do it.

$subcat_terms = get_terms([
  'taxonomy' => 'product_cat'
]);

$subcat_terms generates an array like this:

array (size=3)
0 => 
object(WP_Term)[10551]
  public 'term_id' => int 16
  public 'name' => string 'Hardware' (length=8)
  public 'slug' => string 'hardware' (length=8)
  public 'term_group' => int 0
  public 'term_taxonomy_id' => int 16
  public 'taxonomy' => string 'product_cat' (length=11)
  public 'description' => string '' (length=0)
  public 'parent' => int 0
  public 'count' => int 4
  public 'filter' => string 'raw' (length=3)
  public 'meta_value' => string '0' (length=1)

I tried to check with the php function in_array, but as it has objects, i don’t know how to do this, i would like to check by the term object number or if possible by the term slug. I’ll be grateful if someone helps me.

2 Answers
2

WordPress has the wp_list_pluck function, which can be helpful here. We can make an array of just term IDs from the array of objects like:

$term_ids = wp_list_pluck( $subcat_terms, 'term_id' );

Then we can check in_array:

$this_id = 42;
if( in_array( $this_id, $term_ids ) ){ // do something }

Leave a Comment