Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
} 
like image 377
Gas Avatar asked Aug 09 '15 13:08

Gas


People also ask

How do I get product tags in WooCommerce?

So to create product tags in WooCommerce, fill out the fields for Name, Slug, and Description. Then click the Add New Product Tag button and your job is done. WooCommerce users can also add product tags directly at the time of product creation via the Add product page.

How do I get all products in WooCommerce?

In the WordPress admin, go to WooCommerce > Settings > Products > Product tables. Add your license key and read through all the settings, choosing the ones that you want for your WooCommerce all products list. Now create a page where you want to list all products in a table (Pages > Add New.


1 Answers

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';
}
like image 58
Noman Avatar answered Dec 09 '22 21:12

Noman