我正在尝试从所有产品中获取具有特定产品属性“颜色”的所有自定义术语的数组。
这是我的功能代码:
// custom_terms_taxonomy function
function custom_terms_taxonomy()
{
$custom_terms = array();
// array with products
$products_array = array( 'post_type' => 'product', 'posts_per_page' => -1 );
foreach ( $products_array as $product_array ) {
// attribute string
$terms_array = $product_array->get_attribute( 'pa_color' );
// array with attributes
$terms_array = ! empty($terms_array) ? (array) explode(', ', $terms_array) : array();
foreach ( $terms_array as $term_array ) {
// check if the value exist aleready in array
if (!in_array($term_array, $custom_terms)) {
// add attributes to Custom_array
array_push($custom_terms,$term_array);
}
}
}
return $custom_terms;
}
//output
$att_array=custom_terms_taxonomy();
print_r($att_array);
此脚本无效。任何帮助表示赞赏。
答案 0 :(得分:1)
您的代码中存在一些错误和遗漏的东西……请尝试以下操作:
// custom_terms_taxonomy function
function custom_terms_taxonomy()
{
$custom_terms = array();
// array with products
$products = wc_get_products( array( 'status' => 'publish', 'limit' => -1 ) );
foreach ( $products as $product ) {
// attribute string
$terms_names = $product->get_attribute( 'pa_color' );
// array with attributes
$terms_names_array = ! empty($terms_names) ? (array) explode(', ', $terms_names) : array();
foreach ( $terms_names_array as $terms_name ) {
// check if the value exist aleready in array
if ( !in_array( $terms_name, $custom_terms ) ) {
// add attribute term name in the array
$custom_terms[] = $terms_name;
}
}
}
return $custom_terms;
}
// Raw output
print_r(custom_terms_taxonomy());
经过测试可以正常工作。