1

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.

6

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 }
1

A simple foreach loop can be used to check if a certain slug (or term_id or any other property) is in the results returned by get_terms().

In the following example, $special_term_slugs holds the slugs we'd like to search for. I used an array here so that we can search for multiple slugs, though it's just fine to use only a single slug.

We get all of the terms for the desired taxonomy, product_cat, in this case.

If results are returned, we iterate through them checking to see if the current term object matches one of the slugs defined in our $special_term_slugs array.

// Array of term slugs to check for. Customize as needed.
$special_term_slugs = [
    'hardware',
];

// Attempt to get the terms.
$subcat_terms = get_terms( [
    'taxonomy' => 'product_cat'
] );

// If we get results, search for our special term slugs.
if ( is_array( $subcat_terms ) ) {
    foreach ( $subcat_terms as $subcat_term ) {
        if ( in_array( $subcat_term->slug, $special_term_slugs ) ) {
             // Special term was found. Do something...

        }
    }
}

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.