Home > OS >  Stock quantity shortcode
Stock quantity shortcode

Time:12-11

I'm trying to create a shortcode to place on my single product pages so to display the stock quantity for admins only. For normal customers I just show whether the product is in stock or not. This is the snippet I'm trying to create:

function Product_stock() {
if ( current_user_can( 'administrator' ) ) {
echo '<div ><b>Available Stock (admin):</b><ol>';
   global $product;
   echo wc_get_stock_html( $product );
}
}
add_shortcode( 'Product_stock', 'Product_stock' );

However the above code displays the stock in the format I have it set for my woocommerce store, so it just displays again in this format Availability: In stock or Availability: Out of stock.

What do I need to write to add to get it to print the actual stock value?

CodePudding user response:

One solution is to hook the product availability text.

You can try something like that :

/**
 * WC : add product quantity on front-end only to admins and shop managers
 */
add_filter( 'woocommerce_get_availability_text', 'a3w_woocommerce_get_availability_text', 10, 2);

function a3w_woocommerce_get_availability_text( $availability, $product ) {
    if ( current_user_can( 'manage_woocommerce' ) ) { // replace 'manage_woocommerce' by 'administrator' for admin only OR any other condition
        $availability .= sprintf( ' ( %d )', $product->get_stock_quantity() );
    }
    return $availability;
}, 20, 2 );

This will display something like that to admins :

Availability: In stock ( 18 )

And this to customers :

Availability: In stock

Tested and working.

Place this code in the functions.php in your child theme.

  • Related