我有一个带有woocommerce的商店,我想在类别页面上显示可用的尺寸。我这样做了,但是我想要没有库存的尺码不显示。此时,在类别页面上列出了分配给产品的所有尺寸。我想只显示那些有库存变化的那些。
我尝试向 wc_get_product_terms
添加更多属性,但没有成功。这是当前的代码,工作得很好,但这不是我想要的:
add_action( 'woocommerce_after_shop_loop_item', 'custom_display_post_meta', 9 );
function custom_display_post_meta() {
global $product;
//Doing this for more types of sizes, so list only if it's necesarry
$size = $product->get_attribute('pa_size');
if( $size )
{
$values = wc_get_product_terms( $product->id, 'pa_size', array( 'fields' => 'names' ) );
echo implode( ', ', $values );
}
}
有可能吗?
答案 0 :(得分:1)
您需要浏览变体库存数量,才能在WooCommerce 类别档案“库存”尺寸 >页面,这样:
add_action( 'woocommerce_after_shop_loop_item', 'displaying_sizes_in_stock', 9 );
function displaying_sizes_in_stock() {
global $product;
// HERE, set your attribute taxonomy (once)
$attr_taxonomy = 'pa_size';
$size = $product->get_attribute( $attr_taxonomy );
// Targeting variable products with size attribute (on product category archives)
if( $product->is_type('variable') && $size && is_product_category() ){
$variations = $product->get_available_variations( );
// Product ID - compatibility with WC +3
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
// Iterating Through all available variation for that product
foreach($product->get_available_variations() as $values ){
// Get an instance of WC_Product_Variation object
$variation_obj = wc_get_product( $values['variation_id'] );
// get the defined stock quantity
$stock_quantity = $variation_obj->get_stock_quantity();
if( ! $stock_quantity )
$stock_quantity = $product->get_stock_quantity();
// When product variation is in stock
if( $stock_quantity > 0 && $stock_quantity ){
// Get the variation attributtes
$variation_attributes = $variation_obj->get_variation_attributes();
// For "size" attribute only
if( array_key_exists( "attribute_$attr_taxonomy", $variation_attributes) ){
// Get the term slug
$attr_slug = $variation_attributes["attribute_$attr_taxonomy"];
// Get an instance of WP_Term object
$term_obj = get_term_by( 'slug', $attr_slug, $attr_taxonomy );
// Get the attribute name
$attr_name[] = $term_obj->name;
}
}
}
// Output the "sizes" that have stock
echo implode( ', ', array_unique( $attr_name ) ) . ' ';
}
}
代码进入活动子主题(或主题)的function.php文件或任何插件文件中。
此代码经过测试,适用于wooCommerce版本3 +。