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";
}
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.
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.
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With