Scott Brown
Scott Brown

Reputation: 73

Create a shortcode to display the product stock status on Woocommerce

I would like to display the stock status for example "In Stock" on our product pages, I would ideally like to display the stock status via a custom shortcode.

Does anyone know if this is possible or another solution?

Upvotes: 2

Views: 6632

Answers (2)

Pierre
Pierre

Reputation: 1

Getting a boolean error on get_stock_status

I did the below and it seems to work but unsure if the code is okay.

add_shortcode( 'stock_status', 'display_product_stock_status' );
function display_product_stock_status( $atts) {

    $atts = shortcode_atts(
        array('id'  => get_the_ID() ),
        $atts, 'stock_status'
    );

    $product = wc_get_product( $atts['id'] );
    if(is_bool($product)){
    return '<p></p>';   
    }
    else{
    $stock_status = $product->get_stock_status();

        if('instock' == $stock_status){
            return '<p class="stock in-stock">In Stock</p>';
        }
        else{
            return '<p class="stock out-of-stock">Out of Stock</p>';
        }
}
}

Upvotes: 0

LoicTheAztec
LoicTheAztec

Reputation: 253784

Updated: You can use this simple function to display the stock status with a custom shortcode:

add_shortcode( 'stock_status', 'display_product_stock_status' );
function display_product_stock_status( $atts) {

    $atts = shortcode_atts(
        array('id'  => get_the_ID() ),
        $atts, 'stock_status'
    );

    $product = wc_get_product( $atts['id'] );

    $stock_status = $product->get_stock_status();

    if ( 'instock' == $stock_status) {
        return '<p class="stock in-stock">In stock</p>';
    } else {
        return '<p class="stock out-of-stock">Out of stock</p>';
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

USAGE: [stock_status] (or with defining the product id [stock_status id='47'] where 47 is the product ID…)

Upvotes: 6

Related Questions