Skip to content

Instantly share code, notes, and snippets.

@yiedpozi
Last active June 3, 2021 08:26
Show Gist options
  • Save yiedpozi/334f177b478dacb9e7d54bbd8945de39 to your computer and use it in GitHub Desktop.
Save yiedpozi/334f177b478dacb9e7d54bbd8945de39 to your computer and use it in GitHub Desktop.
Display variation name and its quantity in WooCommerce products management page (table version)
<?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 );
if ( $column === 'total_variations' ) {
if ( $product->is_type( 'variable' ) ) {
$total_variations = count( $product->get_children() );
printf( _n( '%d Variation', '%d Variations', $total_variations, 'woocommerce' ), $total_variations );
$available_variations = $product->get_available_variations();
$total_stock_quantities = 0;
if ( !empty( $available_variations ) ) :
?>
<br>
<br>
<table class="wp-list-table widefat fixed">
<thead>
<tr>
<th style="border-bottom: 1px solid #c3c4c7 !important;"><strong><?php esc_html_e( 'Variation', 'woocommerce' ); ?></strong></th>
<th style="width: 60px; border-bottom: 1px solid #c3c4c7 !important;"><strong><?php esc_html_e( 'Quantity', 'woocommerce' ); ?></strong></th>
</tr>
</thead>
<tbody>
<?php
foreach ( $available_variations as $variation ) :
$product_variation = new WC_Product_Variation( $variation['variation_id'] );
$total_stock_quantities += $product_variation->get_stock_quantity();
?>
<tr>
<td><?php echo $product_variation->get_formatted_name(); ?></td>
<td><?php echo $product_variation->get_stock_quantity() ?: '–'; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<td><strong><?php esc_html_e( 'Total Quantity', 'woocommerce' ); ?></strong></td>
<td><strong><?php echo $total_stock_quantities; ?></strong></td>
</tr>
</tfoot>
</table>
<?php
endif;
} else {
echo '–';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment