要仅在库存变体中显示变量产品的特定属性术语名称,请使用以下方法:
// Utility function: Lightweight SQL query to get instock attribute term names
function get_instock_attribute_term_names( $product_id, $taxonomy ) {
global $wpdb;
return $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT t.name FROM {$wpdb->prefix}posts p
LEFT JOIN {$wpdb->prefix}postmeta pm ON p.ID = pm.post_id
LEFT JOIN {$wpdb->prefix}postmeta pm2 ON p.ID = pm2.post_id
LEFT JOIN {$wpdb->prefix}terms t ON pm2.meta_value = t.slug
LEFT JOIN {$wpdb->prefix}term_taxonomy tt ON t.term_id = tt.term_taxonomy_id
WHERE p.post_type = 'product_variation' AND p.post_status = 'publish'
AND p.post_parent = %d AND pm2.meta_key = '%s'
AND pm.meta_key = '_stock' AND pm.meta_value > 0
AND tt.taxonomy = '%s'
", $product_id, 'attribute_'.$taxonomy, $taxonomy ) );
}
add_action( 'woocommerce_after_shop_loop_item', 'custom_loop_product_meta', 50 );
function custom_loop_product_meta() {
global $product;
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
if( $product->is_type('variable') ) {
$taxonomy = 'pa_size';
$term_names = get_instock_attribute_term_names( $product->get_id(), $taxonomy );
if ( ! empty($term_names) ) {
printf( '<div class="pa-block">%s:<span class="pa-block-text"> %s</span></div>',
esc_html( pll__( 'Sizes' ) ), implode(', ', $term_names) );
}
}
}
代码位于您的子主题的unctions.php文件中(或在插件中).经过测试,效果良好.