Skip to content

Instantly share code, notes, and snippets.

@yiedpozi
Created June 3, 2021 07:30
Show Gist options
  • Save yiedpozi/845ff9063e53207296067c23021866b4 to your computer and use it in GitHub Desktop.
Save yiedpozi/845ff9063e53207296067c23021866b4 to your computer and use it in GitHub Desktop.
Display total stock and total variations in WooCommerce products management page
<?php
add_filter( 'manage_edit-product_columns', 'woocommerce_product_custom_columns' );
function woocommerce_product_custom_columns( $columns ) {
$new_columns = array();
foreach ( $columns as $key => $value ) {
$new_columns[ $key ] = $value;
// Add total variations column after stock status column
if ( $key === 'is_in_stock' ) {
$new_columns['total_variations'] = __( 'Variations', 'woocommerce' );
}
}
return $new_columns;
}
add_action( 'manage_product_posts_custom_column', 'woocommerce_product_custom_columns_value', 30, 2 ); // lower priority, so that we can display stock quantity after the stock status
function woocommerce_product_custom_columns_value( $column, $product_id ) {
$product = wc_get_product( $product_id );
switch ( $column ) {
case 'is_in_stock':
if ( $product->is_type( 'variable' ) ) {
$available_variations = $product->get_available_variations();
$stock = 0;
// Count total stock quantity for every variation
foreach ( $available_variations as $variation ) {
$product_variation = new WC_Product_Variation( $variation['variation_id'] );
$stock += $product_variation->get_stock_quantity();
}
echo sprintf( ' (%d)', $stock );
}
break;
case 'total_variations':
if ( $product->is_type( 'variable' ) ) {
$total_variations = count( $product->get_children() );
printf( _n( '%d Variation', '%d Variations', $total_variations, 'woocommerce' ), $total_variations );
} else {
echo '';
}
break;
}
}
@yiedpozi
Copy link
Author

Thanks very much for this, a very nice little adddition. Made a few clients very happy ;)

You're welcome. Glad to hear that.

@mazlie
Copy link

mazlie commented Jul 4, 2023

Hello. Where to put this code?

@darrenmcentee
Copy link

darrenmcentee commented Jul 4, 2023

Hello. Where to put this code?

You place it in functions.php within your theme.

@mazlie
Copy link

mazlie commented Jul 4, 2023

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment