Skip to content

Instantly share code, notes, and snippets.

@jwad93
Last active September 6, 2023 13:33
Show Gist options
  • Save jwad93/a8fc1cf2b3784e653c3a5c76e1f8ad02 to your computer and use it in GitHub Desktop.
Save jwad93/a8fc1cf2b3784e653c3a5c76e1f8ad02 to your computer and use it in GitHub Desktop.
WooCommerce Parent Stock According to Variable Stock
function wc_get_variable_product_stock_quantity( $output = 'raw', $product_id = 0 ){
global $wpdb, $product;
// Get the product ID (can be defined)
$product_id = $product_id > 0 ? $product_id : get_the_id();
// Check and get the instance of the WC_Product Object
$product = is_a( $product, 'WC_Product' ) ? $product : wc_get_product($product_id);
// Only for variable product type
if( $product->is_type('variable') ){
// Get the stock quantity sum of all product variations (children)
$stock_quantity = $wpdb->get_var("
SELECT SUM(pm.meta_value)
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type = 'product_variation'
AND p.post_status = 'publish'
AND p.post_parent = '$product_id'
AND pm.meta_key = '_stock'
AND pm.meta_value IS NOT NULL
");
wc_update_product_stock( $product, $stock_quantity , 'set' );
// Preparing formatted output
if ( $stock_quantity > 0 ) {
$html = '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
} else {
if ( is_numeric($stock_quantity) )
$html = '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
else
$html = '';
}
// Different output options
if( $output == 'echo_html' )
echo $html;
elseif( $output == 'return_html' )
return $html;
else
return $stock_quantity;
}
}
add_action( 'woocommerce_single_product_summary', 'display_variable_product_stock_quantity', 15 );
function display_variable_product_stock_quantity(){
wc_get_variable_product_stock_quantity( 'echo_html' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment