9th April 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

Alok design digital experiences to help businesses achieve their goals. He is passionate about designing right User Experience for their customers. For over 15 years, he have worked with small startups to mature product teams. Whether it is designing a WordPress product, a frontend experience, WooCommerce, Shopify, he follow the best product development practices for design and code, for desktop or mobile.