我正在尝试根据(pa\\U product-series)中的属性值创建产品循环。许多产品可以有相同的价值,但我只想从每个产品中返回一个。。。避免使用价值相同的多个产品。
示例(xxxx是产品系列):
产品1-x400产品2-x400产品3-x500产品4-x600产品5-x600
结果应仅显示产品1、产品3和产品4。
这是我到目前为止的代码,但它返回的是一个空数组
global $product;
$prod_series = $product->get_attribute( \'pa_product-series\' );
$postid = get_the_ID();
$args = array(
\'post_type\' => \'product\',
\'orderby\' => \'title\',
\'order\' => \'asc\',
\'posts_per_page\' => 10,
\'tax_query\' => array(
\'relation\' => \'\', array(
\'taxonomy\' => \'pa_product-series\',
\'field\' => \'slug\',
\'terms\' => $prod_series
),
)
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ):
$term_names = array();
while ( $loop->have_posts() ):
$loop->the_post();
foreach( wc_get_product_terms($loop->post->ID, \'pa_product-series\' ) as $attribute_value ):
$term_names[$attribute_value] = $attribute_value;
endforeach;
endwhile;
print_r($attribute_value);
else:
echo \'<span>No SKUs matches found</span>\';
endif;
wp_reset_postdata();
当我使用print\\u r($attribute\\u value)时,它返回以下内容:
WP_Term Object (
[term_id] => 1687
[name] => CT0201CSF
[slug] => ct0201csf
[term_group] => 0
[term_taxonomy_id] => 1687
[taxonomy] => pa_product-series
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
[term_order] => 0
)
WP_Term Object (
[term_id] => 1687
[name] => CT0201CSF
[slug] => ct0201csf
[term_group] => 0
[term_taxonomy_id] => 1687
[taxonomy] => pa_product-series
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
[term_order] => 0
)
我需要将每个term\\u id或名称限制为1个结果。。。
SO网友:Mike Baxter
使用the developers\' reference 例如,您正在冗余地引用$循环。删除$loop->
之前the_post()
和have_posts()
:
if ( have_posts() ) {
$term_names = array();
while ( have_posts() ) {
the_post();
$myPostID = get_the_ID();
//Uncomment next 3 lines to debug using your error log
//ob_start();
//var_dump($myPostID);
//error_log(\'myPostID = \' . ob_get_clean(),0);
$arrProductTerms = wc_get_product_terms( $myPostID, \'pa_product-series\' );
//Uncomment next 3 lines to debug using your error log
//ob_start();
//var_dump($arrProductTerms);
//error_log(\'arrProductTerms = \' . ob_get_clean(),0);
foreach($arrProductTerms as $att){
// prevent later values from overwriting existing...
// Also, I believe $att is an object with properties, so you need to choose which one should be unique. I chose "slug"
if (!array_key_exists($att->slug,$term_names)) $term_names[$att->slug]=$att;
} // loop foreach
} // loop while
// sort by key ($att->slug)
ksort($term_names);
// Used array_keys because we stored $att as objects
echo \'<span>\' . implode( \'</span>, <span>\', array_keys($term_names) ) . \'</span> \';
} else {
echo \'<span>No SKUs matches found</span>\';
} // end if
如果那不明白,我会用
error_log()
调用以仔细检查的输出
wc_get_product_terms()
看看你是否得到了你想要的。