Created
June 3, 2021 07:30
-
-
Save yiedpozi/845ff9063e53207296067c23021866b4 to your computer and use it in GitHub Desktop.
Display total stock and total variations in WooCommerce products management page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Hello. Where to put this code?
Hello. Where to put this code?
You place it in functions.php within your theme.
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're welcome. Glad to hear that.