Reputation: 13
I have a store with woocommerce and I want to show the available size at the category page. I did that, but I want sizes not in stock to not show. In this moment on category page are listed all sizes assigned to the product. I want to display only the ones that have variations asigned to them that are in stock.
I tried adding more attributes to wc_get_product_terms
but with no success. This is the current code, working pretty well but it's not what I want:
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 );
}
}
Is it possible?
Upvotes: 1
Views: 1449
Reputation: 253804
You need to go through the variations stock quantity, to display only "in stock" sizes for each variable products, in WooCommerce category archives pages, this way:
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 ) ) . ' ';
}
}
The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works for wooCommerce versions 3+.
Upvotes: 2