Skip to content

Instantly share code, notes, and snippets.

@braddalton
Last active December 19, 2023 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save braddalton/6ec1da573bc98f6bfabb1454197f2d74 to your computer and use it in GitHub Desktop.
Save braddalton/6ec1da573bc98f6bfabb1454197f2d74 to your computer and use it in GitHub Desktop.
WooCommerce Show How Many Products Left in Stock - Full Tutorial & Support https://wpsites.net/?p=114708
/**
* @author Brad Dalton
* @link https://wpsites.net/?p=114708
* @copyright https://wpsites.net/disclosure-privacy/
*/
// Hook to display stock quantity on the product page
add_action( 'woocommerce_before_add_to_cart_button', 'display_stock_quantity', 10 );
// Function to display stock quantity for each product
function display_stock_quantity() {
global $product;
// Check if WooCommerce is active
if ( class_exists( 'WooCommerce' ) ) {
// Check if stock management is unchecked
$stock_managed = $product->get_manage_stock();
if ( ! $stock_managed && $product->is_in_stock() ) {
echo '<p>' . __('Not many left') . '</p>';
} else {
// Check if the product is variable or simple
if ( $product->is_type( 'variable' ) ) {
// For variable products, get stock quantity for each variation
$variations = $product->get_available_variations();
foreach ( $variations as $variation ) {
$variation_id = $variation['variation_id'];
$variation_obj = wc_get_product( $variation_id );
$stock_quantity = $variation_obj->get_stock_quantity();
echo '<p>' . ( $stock_quantity > 0 ? __('Only') . ' ' . $stock_quantity . ' left in stock' : 'Out of Stock' ) . '</p>';
}
} else {
// For simple products, get stock quantity
$stock_quantity = $product->get_stock_quantity();
echo '<p>' . ( $stock_quantity > 0 ? __('Only') . ' ' . $stock_quantity . ' left in stock' : 'Out of Stock' ) . '</p>';
}
}
}
}
// Hook to remove default stock status message
add_filter('woocommerce_get_stock_html', 'remove_default_stock_status', 10, 2);
// Function to remove default stock status message
function remove_default_stock_status($html, $product) {
// Check if stock management is enabled for the product
$stock_managed = $product->get_manage_stock();
if ($stock_managed) {
$html = '';
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment