我想在一个数组中获取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";
}
答案 0 :(得分:12)
您需要循环遍历数组并创建一个单独的数组来检查in_array
,因为get_terms
会在数组中返回object
。
$terms = get_terms( 'product_tag' );
$term_array = array();
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
$term_array[] = $term->name;
}
}
所以,循环遍历数组。
您可以使用 in_array()。
假设$term_array
包含标记黑色
if(in_array('black',$term_array)) {
echo 'black exists';
} else {
echo 'not exists';
}
答案 1 :(得分:2)
我必须将args-array解析为get_terms函数。也许这有助于其他人。
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_tags = get_terms( 'product_tag', $args );
答案 2 :(得分:0)
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_tags = get_terms( 'product_tag', $args );
//only start if we have some tags
if ( $product_tags && ! is_wp_error( $product_tags ) ) {
//create a list to hold our tags
echo '<ul class="sb-tag">';
//for each tag we create a list item
foreach ($product_tags as $tag) {
$tag_title = $tag->name; // tag name
$tag_link = get_term_link( $tag );// tag archive link
echo '<li class="sidebar-list-tag" ><a href="'.$tag_link.'"> <span>'.$tag_title.' </span></a></li>';
}
echo '</ul>';
}
答案 3 :(得分:0)
import 'dart:convert';
import 'package:NewsApp/model/article_model.dart';
import 'package:http/http.dart';
class ApiService {
final endPointUrl =
"http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=6ef7ae62a9e74ca2bcc7d634f9985146";
Future<List<Article>> getArticle() async {
Response res = await get(endPointUrl);
if (res.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(res.body);
List<dynamic> body = json['articles'];
List<Article> articles =
body.map((dynamic item) =>
Article.fromJson(item)).toList();
return articles;
} else {
throw ("Can't get the Articles");
}
}
}