开发支持WooCommerce简单/可变产品的库存状态查询短代码
Alright, let's build that custom shortcode you need for WooCommerce. This will handle both simple and variable products exactly as you described, checking stock status properly:
Custom WooCommerce Shortcode for Global Stock Status Display
Here's the complete code you can use:
function wc_product_stock_status_shortcode() { global $product; // Exit if we're not on a valid product page if ( ! is_a( $product, 'WC_Product' ) ) { return ''; } $stock_status = 'Out of stock'; // Handle simple product stock check if ( $product->is_type( 'simple' ) ) { if ( $product->get_stock_quantity() > 0 && $product->is_in_stock() ) { $stock_status = 'In stock'; } } // Handle variable product stock check (check all variations) elseif ( $product->is_type( 'variable' ) ) { $variations = $product->get_available_variations(); foreach ( $variations as $variation ) { $variation_product = wc_get_product( $variation['variation_id'] ); // If any variation has stock, update status and break the loop if ( $variation_product->get_stock_quantity() > 0 && $variation_product->is_in_stock() ) { $stock_status = 'In stock'; break; } } } // Return formatted status with a CSS class for easy styling return '<p class="product-stock-status">' . esc_html( $stock_status ) . '</p>'; } add_shortcode( 'product_stock_status', 'wc_product_stock_status_shortcode' );
How it works:
- We start by targeting the current product on the page using the global
$productobject. - Default status is set to "Out of stock" — we only override this if we find available inventory.
- For simple products: We check both the stock quantity and the product's official in-stock flag (covers edge cases where stock management is enabled but quantity is set to 0).
- For variable products: We loop through all available variations. As soon as we find one with active stock, we update the status and stop checking (saves unnecessary processing).
- The output is wrapped in a paragraph with a custom CSS class (
product-stock-status) so you can style it to match your store's design.
How to use:
- Add this code to your child theme's
functions.phpfile, or use a custom code snippet plugin (like Code Snippets) to avoid losing changes when your theme updates. - On any product page (in the description, short description, or even a custom product tab), insert the shortcode
[product_stock_status]where you want the stock status to appear.
Quick customization tip: If you want to use different wording (like "Available" instead of "In stock"), just edit the string values in the code to match your preferred text.
内容的提问来源于stack exchange,提问作者Garconis
相关产品推荐
相关产品推荐

