php – 显示Woocommerce存档页面中所有产品类型的库存可用性

我在使用此代码显示产品库存:

    add_action( 'woocommerce_after_shop_loop_item', 'display_variable_product_stock_quantity', 10 );
function display_variable_product_stock_quantity(){
    wc_get_variable_product_stock_quantity( 'echo_html' );
} 

function show_stock() {
global $product;
if ( $product->stock ) { // if manage stock is enabled 
if ( ! $product->managing_stock() && ! $product->is_in_stock() )
        echo '';
}
if ( number_format($product->stock,0,'','') > 0 ) { // if stock is low
echo '<div class="remainingpc" style="text-align:center;"><font color="red"> ' . number_format($product->stock,0,'','') . ' Pcs Left</font></div>';
} 
else {
echo '<div class="remaining" style="text-align:center;"><font color="red">Out of Stock</font></div>'; 
}
}

add_action('woocommerce_after_shop_loop_item','show_stock', 10);

如果产品是变量,我使用此答案代码显示库存可用性:
Get the total stock of all variations from a variable product In Woocommerce

如何在单个条件函数中合并此代码?

例如.如果产品是简单产品,则不会显示变量产品的其他代码.

解决方法:

以下将处理作为商店的woocommerce存档产品页面中所有产品类型的库存可用性的显示.

要处理除变量之外的其他产品类型的库存可用性显示,您可以使用专用函数wc_get_stock_html()代替,这将简化代码.

add_action( 'woocommerce_after_shop_loop_item', 'wc_loop_get_product_stock_availability_text', 10 );
function wc_loop_get_product_stock_availability_text() {
    global $wpdb, $product;

    // For variable products
    if( $product->is_type('variable') ) {

        // Get the stock quantity sum of all product variations (children)
        $stock_quantity = $wpdb->get_var("
            SELECT SUM(pm.meta_value) FROM {$wpdb->prefix}posts as p
            JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
            WHERE p.post_type = 'product_variation'
            AND p.post_status = 'publish' AND p.post_parent = '".get_the_id()."'
            AND pm.meta_key = '_stock' AND pm.meta_value IS NOT NULL
        ");

        if ( $stock_quantity > 0 ) {
            echo '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
        } else {
            if ( is_numeric($stock_quantity) )
                echo '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
            else
                return;
        }
    }
    // Other products types
    else {
        echo wc_get_stock_html( $product );
    }
}

代码位于活动子主题(或活动主题)的function.php文件中.经过测试和工作.

上一篇:php – 按属性值减少WooCommerce项目库存


下一篇:USACO Stock Market