April 9, 2015 in Snippets, Wordpress

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.

About the author

Alok Jain

As a Frontend Developer and Founder, I blend technical skills with entrepreneurial drive. Skilled in crafting intuitive user interfaces, I bridge design and development for seamless digital experiences. Beyond work, I'm passionate about Philately, sharing my collection, and connecting with fellow enthusiasts in both tech and stamp collecting communities.

2 thoughts on “Product Quantity Shortcode WooCommerce

  1. Valle says:

    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

    1. Alok Jain says:

      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”.

Leave a Reply

Your email address will not be published. Required fields are marked *