Gas
Gas

Reputation: 737

Woocommerce Get product tags in array

I want to get the product tags of the woocommerce products in an array, for doing if/else logic with it (in_array), but my code doesn't work:

<?php 

$aromacheck = array() ; 
$aromacheck = get_terms( 'product_tag') ; 
// echo $aromacheck

?>

When echoing $aromacheck, I only get empty Array, though the product tags are existing - visible in the post class.

How can I get the product tags in an array correctly?

Solution (thanks Noman and nevius):

/* Get the product tag */
$terms = get_the_terms( $post->ID, 'product_tag' );

$aromacheck = array();
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        $aromacheck[] = $term->slug;
    }
}

/* Check if it is existing in the array to output some value */

if (in_array ( "value", $aromacheck ) ) { 
   echo "I have the value";
} 

Upvotes: 21

Views: 56810

Answers (3)

Bibek Sigdel
Bibek Sigdel

Reputation: 41

global $product;
$tags = $product->tag_ids;
foreach($tags as $tag) {
   echo get_term($tag)->name;
}

Upvotes: 4

Unicco
Unicco

Reputation: 2580

I had to parse an args-array to the get_terms function. Maybe this help other aswell.

$args = array(
    'number'     => $number,
    'orderby'    => $orderby,
    'order'      => $order,
    'hide_empty' => $hide_empty,
    'include'    => $ids
);

$product_tags = get_terms( 'product_tag', $args );

Upvotes: 3

Noman
Noman

Reputation: 4116

You need to loop through the array and create a separate array to check in_array because get_terms return object with in array.

$terms = get_terms( 'product_tag' );
$term_array = array();
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        $term_array[] = $term->name;
    }
}

So, After loop through the array.

You can use in_array().
Suppose $term_array contains tag black

if(in_array('black',$term_array)) {
 echo 'black exists';
} else { 
echo 'not exists';
}

Upvotes: 28

Related Questions