Skip to content
Advertisement

Check if WooCommerce product (simple or variations) are in stock and display label as shortcode

I would like to have a shortcode that I can add to a WooCommerce product page. The shortcode would simply check the product stock and say “In stock” if it has any. And then “Out of stock” if the product (or any of the variations) don’t have inventory.

This shortcode should work for both Simple products and Variable products. With Simple products, it would just check the stock quantity. For Variable products, it would check the stock quantity of ALL of the variations (since the variable product inventory is managed at the inventory level). If ANY of the variations have stock, then it would still return as “In stock”.

It would only say “Out of stock” if ALL of the variations of a particular product were 0.

I plan to use this shortcode within a product page template I am building.

Advertisement

Answer

For now I’ve created this by:

/* Create stock checker of overall product */
add_shortcode( 'fs-product-stock-status', 'fs_product_stock_status_shortcode' );
function fs_product_stock_status_shortcode( $atts ) {
    // begin output buffering
    ob_start();

    $stockstatus = get_post_meta( get_the_ID(), '_stock_status', true );

    if ($stockstatus == 'outofstock') {
        echo '<p class="stock out-of-stock">Out of stock</p>';
    }
    elseif ($stockstatus == 'instock') {
        echo '<p class="stock in-stock">In stock</p>';
    }

    // end output buffering, grab the buffer contents, and empty the buffer
    return ob_get_clean();
}

But I’m open to other solutions that may be better. This seems to be working though.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement