我想获取数组中 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/