Woocommerce获取阵列中的产品标签

Gas*_*Gas 9 wordpress woocommerce

我想在一个数组中获取woocommerce产品的产品标签,用它做if/else逻辑(in_array),但我的代码不起作用:

<?php 

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

?>
Run Code Online (Sandbox Code Playgroud)

当回显$ aromacheck时,我只获得空数组,尽管产品标签存在 - 在帖子类中可见.

如何正确获取阵列中的产品标签?

解决方案(感谢Noman和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";
} 
Run Code Online (Sandbox Code Playgroud)

Nom*_*man 13

您需要遍历数组并创建一个单独的数组来检查,in_array因为get_terms返回object数组.

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

所以,循环后通过数组.

你可以使用in_array().
假设$term_array包含标签黑色

if(in_array('black',$term_array)) {
 echo 'black exists';
} else { 
echo 'not exists';
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,就是这样,我输入 `$terms = get_the_terms( $post-&gt;ID, 'product_tag' );` 并且效果很好!我编辑了我的帖子以包含完整的解决方案。 (2认同)