// Check if function show_specific_product_quantity exists or not.
if ( ! function_exists( 'show_specific_product_quantity' ) ) {
/**
* Return product stock quantity.
*
* @param array $atts Shortcode attritube.
* @return int Number of stock for the particular product ID.
*/
function show_specific_product_quantity( $atts ) {
// Shortcode Attributes.
$atts = shortcode_atts(
array(
'id' => '', // Product ID argument.
),
$atts,
'product_qty'
);
if ( empty( $atts['id'] ) ) {
return;
}
$stock_quantity = 0;
// Check if pass Product ID is valid WooCommerce product.
if ( 'product' !== get_post( $atts['id'] )->post_type ) {
return 'Kindly check product ID';
}
$product_obj = wc_get_product( intval( $atts['id'] ) );
// Check if Manage stock is enable or not.
if ( $product_obj->get_manage_stock() ) {
$stock_quantity = $product_obj->get_stock_quantity();
} else {
return 'Manage stock not available for this product.';
}
if ( $stock_quantity > 0 ) {
return $stock_quantity;
} else {
return 'No stock available.';
;
}
}
}
// Add Shortcode to get product quantity
// i.e. [product_qty id="{product_id_number}"].
add_shortcode( 'product_qty', 'show_specific_product_quantity' );
Нужно проверить еще несколько вещей, например 1. Был ли передан действительный идентификатор продукта или нет.2. Затем, если для Продукта включено управление запасами.