问题
I'm using WooCommerce: Display stock quantity for a given product ID on normal Pages or Posts amazing answer code that works to display the product quantity for a WooCommerce product in any page or post via a shortcode.
I would like to only display the exact quantity up to 5 products in stock and have "More than 5" for any quantity of 6 or more.
Can it be done by modifying this code?
回答1:
The following should do the trick:
if( !function_exists('show_specific_product_quantity') ) {
function show_specific_product_quantity( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts(
array(
'id' => '', // Product ID argument
),
$atts,
'product_qty'
);
if( empty($atts['id'])) return;
$stock_quantity = 0;
$product_obj = wc_get_product( intval( $atts['id'] ) );
$stock_quantity = $product_obj->get_stock_quantity();
if( $stock_quantity > 0 && $stock_quantity <= 5 )
return $stock_quantity;
elseif( $stock_quantity > 5 )
return __("More than 5", "woocommerce");
}
add_shortcode( 'product_qty', 'show_specific_product_quantity' );
}
Code goes in function.php file of your active child theme (or active theme). It should work.
Original answer: WooCommerce: Display stock quantity for a given product ID on normal Pages or Posts
回答2:
You could try adding to this line
if( $stock_quantity > 0 ) return $stock_quantity;
try:
$overQty = "More than 5";
if( $stock_quantity > 5 ){ return $overQty } else { return $stock_quantity };
it should work
来源:https://stackoverflow.com/questions/53856097/display-custom-stock-quantity-conditionally-via-shortcode-on-woocommerce