wordpress - Woocommerce 获取数组中的产品标签

标签 wordpress woocommerce

我想获取数组中 woocommerce 产品的产品标签,以便用它执行 if/else 逻辑(in_array),但我的代码不起作用:

<?php 

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

?>

当回显 $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";
} 

最佳答案

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

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

因此,After 循环遍历数组。

您可以使用in_array()
假设 $term_array 包含标签 black

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

关于wordpress - Woocommerce 获取数组中的产品标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904758/

相关文章:

python - 在 python-wordpress-xmlrpc 请求上设置自定义 header

javascript - 从 Woocommerce get_customer_location Ajax 事件中删除

php - 将收到的数据保存到 Woocommerce 3 中来自外部交付服务的订单

wordpress - 使用其他产品作为选项 - WooCommerce

wordpress - 使用借记卡或信用卡的 Woocommerce Paypal Pay 间歇性不显示

javascript - 使用 parallax.min.js 将空白添加到视差 div

css - buddypress css文件放在哪里

css - 制作没有图像的 Woocommerce 产品子类别小盒子

php - 如何动态更改 Woocommerce 中的 PayPal 地址?

php - 在单独的行中显示 woocommerce 产品尺寸