在Woocommerce 3中检查产品库存可用性

时间:2019-03-09 10:15:59

标签: php wordpress woocommerce product stock

我有以下代码,在商店/存档页面上添加了有关库存可用性和运送到产品的简单通知,但是如果产品库存数量为0(缺货),则不会显示通知。

add_action( 'woocommerce_after_shop_loop_item','show_stock_shop', 90 );

function show_stock_shop() {
    global $product;

    $regular = $product->regular_price;
    $sale = $product->sale_price;
//  $stock = the_field('stock-available');

    if ( $product->stock ) { // if manage stock is enabled 
        if ( $product->get_stock_quantity() > 0 && $regular >= 500 || $sale >= 500  ) { // in stock, free shipping
            echo '<div class="remaining text-center pt-2 pb-2">Skladom. <span class="doprava-zadarmo">Doprava zadarmo</span></div>';
        } elseif ( $product->get_stock_quantity() == 0 && $regular >= 500 || $sale >= 500 ) { // out of stock, free shipping
            echo '<div class="remaining text-center pt-2 pb-2"><s>(nie je skladom)</s>. <span class="doprava-zadarmo">Doprava zadarmo</span></div>';
        } elseif ( $product->get_stock_quantity() > 0 && $regular < 500 || $sale < 500 ) { // in stock, not free shipping
            echo '<div class="remaining text-center pt-2 pb-2">Skladom. <span class="doprava-zadarmo">Doprava zadarmo od 500 eur</span></div>';
        } elseif ( $product->get_stock_quantity() == 0 && $regular < 500 || $sale < 500 ) { // out of stock, not free shipping
            echo '<div class="remaining text-center pt-2 pb-2"><s>(nie je skladom)</s>. <span class="doprava-zadarmo">Doprava zadarmo od 500 eur</span></div>';
        } else {
            echo '<div class="remaining text-center pt-2 pb-2">Do ' . /*$stock .*/ ' dní</div>'; 
        }
    }
}

enter image description here

1 个答案:

答案 0 :(得分:2)

您的代码已过时。从Woocommerce 3开始,无法直接访问产品属性,您应使用available WC_Product methods之类的is_in_stock() conditional method 检查产品库存可用性

尝试以下简化的代码版本:

add_action( 'woocommerce_after_shop_loop_item', 'display_loop_item_stock_notice', 90 );
function display_loop_item_stock_notice() {
    global $product;

    // For active product price: Free shipping || NO Free shipping
    $text = $product->get_price() >= 500 ? __("Doprava zadarmo") : __("Doprava zadarmo od 500 eur");

    // In stock
    if ( $product->is_in_stock() ) { 
        $text = __("Skladom.") . ' <span class="doprava-zadarmo">' . $text . '</span>';
    } 
    // Out of stock
    else {
        $text = '<s>(' . __("nie je skladom") . ')</s> <span class="doprava-zadarmo">' . $text . '</span>';
    }
    echo '<div class="remaining text-center pt-2 pb-2">' . $text . '</div>';
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。