在 Woocommerce 中获取可变产品的所有变体的总库存

Erw*_*ang 3 php wordpress product stock woocommerce

在 woocommerce 中,我想显示可变产品中所有变体的总库存。每个产品变体的库存在产品变体级别进行管理。

如果我用于可变产品:

global $product;

echo $product->get_stock_quantity();
Run Code Online (Sandbox Code Playgroud)

我没有得到该产品所有变体的总库存。

是否可以从 Woocommerce 中的可变产品中获取所有变体的总库存?

Loi*_*tec 5

以下自定义函数将显示可变产品(仅限)的所有产品变体库存数量的总和。

它使用一个非常轻量级的 SQL 查询,从一个变量产品中得出所有子变量的总和。

注意:库存需要在产品变异级别进行管理。

function wc_get_variable_product_stock_quantity( $output = 'raw', $product_id = 0 ){
    global $wpdb, $product;

    // Get the product ID (can be defined)
    $product_id = $product_id > 0 ? $product_id : get_the_id();

    // Check and get the instance of the WC_Product Object
    $product = is_a( $product, 'WC_Product' ) ? $product : wc_get_product($product_id);

    // Only for variable product type
    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 = '$product_id'
            AND pm.meta_key = '_stock'
            AND pm.meta_value IS NOT NULL
        ");

        // Preparing formatted output
        if ( $stock_quantity > 0 ) {
            $html = '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
        } else {
            if ( is_numeric($stock_quantity) )
                $html = '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
            else
                $html = '';
        }

        // Different output options
        if( $output == 'echo_html' )
            echo $html;
        elseif( $output == 'return_html' )
            return $html;
        else
            return $stock_quantity;
    }
}
Run Code Online (Sandbox Code Playgroud)

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


用法(3例):

1)在php代码的任何地方,获取库存数量(来自动态 $product_id):

$stock_quantity = wc_get_variable_product_stock_quantity( 'raw', $product_id );
Run Code Online (Sandbox Code Playgroud)

2)显示在商店和档案页面(以价格范围为例):

add_action( 'woocommerce_after_shop_loop_item_title', 'display_variable_product_stock_quantity', 20 );
function display_variable_product_stock_quantity(){
    wc_get_variable_product_stock_quantity( 'echo_html' );
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。

在此处输入图片说明


3) 单品页面展示(以价格区间为例):

add_action( 'woocommerce_single_product_summary', 'display_variable_product_stock_quantity', 15 );
function display_variable_product_stock_quantity(){
    wc_get_variable_product_stock_quantity( 'echo_html' );
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。

在此处输入图片说明