Woocommerce 获取数组中的产品标签

编程入门 行业动态 更新时间:2024-10-22 21:35:43
本文介绍了Woocommerce 获取数组中的产品标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

?>

当回显 $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?

解决方案(感谢 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 返回 <代码>对象与数组.

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;
    }
}

所以,After 遍历数组.

So, After loop through the array.

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

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

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

这篇关于Woocommerce 获取数组中的产品标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-25 06:45:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1080233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   标签   产品   Woocommerce

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!