且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 23:10:28

以下内容将显示woocommerce存档产品页面中所有产品类型的库存状况,如商店.

The following will handle the display of the stock availability for all product types in woocommerce archive product pages as shop.

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

To handle the stock availability display for other product types than variable, you can use the dedicated function wc_get_stock_html() instead, which will simplify the code.

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文件中.经过测试,可以正常工作.

Code goes in function.php file of your active child theme (or active theme). Tested and works.