我想做这个东西 - 获取具有已知 id 的类别中产品的某些属性的选项列表。因此,类别 id 是 $catid,属性是 $attr。
所以,在我看来,我必须执行以下步骤: 0) 获取 id 为类别的所有产品 id
最后必须有一个像[s,m,l,xl,xxl]这样的数组,例如,如果搜索属性是“size”,类别是“T恤”。
所以做了什么:
function get_options_of_attribute() {
$catid = "6776"; // T-shirts
$attr = "size";
$all_ids = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $current_cat_id,
'operator' => 'IN'
)
),
));
$ids = '';
$values = '';
foreach ( $all_ids as $id ) {
$ids .= $id.' ';
foreach( wc_get_product_terms( $id, $attr ) as $attribute_value ){
$values .= $attribute_value.' ';
}
}
//返回$ids;
return $values;
}
add_shortcode( 'listofoptions', 'get_options_of_attribute' );
什么也没发生。生成 $ids 的代码部分正在工作,我认为 wc_get_product_terms() 有问题......
最后我解决了:
function get_options_of_attribute() {
$current_cat_id = "6776"; // T-shirts
$attr = "size";
$all_ids = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $current_cat_id,
'operator' => 'IN'
)
),
));
$ids = '';
$value = array();
$values = '';
foreach ( $all_ids as $id ) {
$ids .= $id.' ';
$value[] = wc_get_product_terms($id,'pa_'.$attr, array( 'fields' => 'names'))[0];
}
$uniquevalue = array_unique($value);
foreach ( $uniquevalue as $uv ) {
$values .= $uv.' ';
}
return $values;
}
add_shortcode( 'listofoptions', 'get_options_of_attribute' );
感谢您的解决方案。就我而言,它仅返回 8 个术语中的 2 个。为了调试,我让它显示在类别中找到的分类法,所以这里是固定脚本:
add_action('woocommerce_before_main_content', function() {
$current_cat_id = "335"; // Adjust the category ID accordingly
$attr = "size";
$all_ids = get_posts([
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => [
[
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $current_cat_id,
'operator' => 'IN',
]
],
]);
$values = [];
foreach ($all_ids as $id) {
// Fetch all terms for each product
$product_terms = wp_get_post_terms($id, 'pa_' . $attr, ['fields' => 'names']);
if (!is_wp_error($product_terms)) {
$values = array_merge($values, $product_terms);
}
}
$unique_values = array_unique($values);
// Echo unique values separated by space
echo implode(' ', $unique_values);
});