简体   繁体   English

检查 WooCommerce 产品(简单或变体)是否有库存并将标签显示为短代码

[英]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.我想要一个可以添加到 WooCommerce 产品页面的短代码。 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.对于 Simple 产品,它只会检查库存数量。 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.如果特定产品的所有变体都为 0,它只会说“缺货”。

I plan to use this shortcode within a product page template I am building.我计划在我正在构建的产品页面模板中使用这个短代码。

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.不过,这似乎有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM