问题描述
限时送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:关键词]
发布评论