Woocommerce 获取数组中的产品标签
Woocommerce Get product tags in array
我想获取数组中 woocommerce 产品的产品标签,以便用它执行 if/else 逻辑 (in_array),但我的代码不起作用:
<?php
$aromacheck = array() ;
$aromacheck = get_terms( 'product_tag') ;
// echo $aromacheck
?>
回显 $aromacheck 时,我只得到空数组,尽管产品标签存在 - 在 post class 中可见。
如何正确获取数组中的产品标签?
解决方案(感谢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
return 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';
}
我必须将 args 数组解析为 get_terms 函数。也许这对其他人也有帮助。
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_tags = get_terms( 'product_tag', $args );
global $product;
$tags = $product->tag_ids;
foreach($tags as $tag) {
echo get_term($tag)->name;
}
我想获取数组中 woocommerce 产品的产品标签,以便用它执行 if/else 逻辑 (in_array),但我的代码不起作用:
<?php
$aromacheck = array() ;
$aromacheck = get_terms( 'product_tag') ;
// echo $aromacheck
?>
回显 $aromacheck 时,我只得到空数组,尽管产品标签存在 - 在 post class 中可见。
如何正确获取数组中的产品标签?
解决方案(感谢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
return 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';
}
我必须将 args 数组解析为 get_terms 函数。也许这对其他人也有帮助。
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_tags = get_terms( 'product_tag', $args );
global $product;
$tags = $product->tag_ids;
foreach($tags as $tag) {
echo get_term($tag)->name;
}