Product Quantity Shortcode WooCommerce
Custom WordPress Shortcode to show product quantity available in stock. Make sure you have added product quantity in inventory section of product.
(Similar shortcodes can also be created for other product details if needed)
<?php
// [show_qty id="product_id"]
function show_qty_func( $atts ) {
$p = shortcode_atts( array(
'id' => 0
), $atts );
$_pf = new WC_Product_Factory();
$_product = $_pf->get_product($p['id']);
// from here $_product will be a fully functional WC Product object,
// you can use all functions as listed in their api:
// http://docs.woothemes.com/wc-apidocs/class-WC_Product.html
return $_product->get_stock_quantity();
}
add_shortcode( 'show_qty', 'show_qty_func' );
?>
Note: If you are not familiar with wordpress themes, you need to add this code in functions.php
in your theme’s folder.
Hello,
Is there any way how to make this code show “In Stock” or “Out of Stock” messages instead of the quantity number? I would really appreciate some help on this.
Sincrerely,
Cannot-code-for-my-life Valle
I didn’t tried this, but you can try adding a condition before return statement, to check if value of $_product->get_stock_quantity() is greater then 0, return “In Stock”, else return “Out of Stock”.