获得“有货"的数量. Woocommerce中可变产品的产品变体 [英] Get the count of "in stock" product variations for a variable product in Woocommerce

查看:187
本文介绍了获得“有货"的数量. Woocommerce中可变产品的产品变体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为functions.php文件制作一个片段,该片段仅显示所选变体的一个价格,从而省略了单个产品页面上显示的价格范围以及变体价格.我正在使用以下代码:

I'm trying to make a snippet for functions.php file that shows only one price of selected variation, thus omitting the price range displayed along with variation price on single product page. I'm using the following code:

    add_action( 'woocommerce_before_single_product', 'my_remove_variation_price' );
$product_variations=$product_variable->get_available_variations;
function my_remove_variation_price() {
  global $product;
  if ( $product->is_type( 'variable' ) {
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
  }
}

问题是,例如,当您有一个单一产品的两个变体而一个缺货时,此脚本在单个产品页面上隐藏了剩余一个变体的价格. 我当时想也许每个产品都有COUNT个可用变体,然后使用IF使用标准的单个产品模板来显示它们.或者,也许您有更好的主意该如何解决?

The problem is when you have, for instance, two variations of single product and one goes out of stock, this script hides the price of one remaining variation on single product page. I was thinking maybe to have a COUNT of available variations per product and use IF to show them using standard single product template. Or maybe you have better idea how to solve that?

推荐答案

要获取单个产品页面上某个变量产品的现货"变化计数,您可以:

To get the "in stock" variations count of a variable product on single product pages you can:

1)仅使用php和Woocommerce WC_Product方法:

1) Use only php and Woocommerce WC_Product methods:

global $product;
$count_in_stock = 0;

if ( $product->is_type( 'variable' ) ) {
    $variation_ids = $product->get_children(); // Get product variation IDs

    foreach( $variation_ids as $variation_id ){
        $variation = wc_get_product($variation_id);
        if( $variation->is_in_stock() )
            $count_in_stock++;
    }
}

// Your condition
if( $count_in_stock <= 1 ){
   // Do something
}

2)使用带有少量php(快速又轻巧)的SQL查询:

2) Use a SQL query with few php (quick and lighter):

global $wpdb, $product;
$product_id = $product->get_id();
$count_in_stock = 0;

if ( $product->is_type( 'variable' ) ) {
    $count = $wpdb->get_col("
        SELECT count(p.ID) as in_stock_count FROM {$wpdb->prefix}postmeta as pm
        INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
        WHERE p.post_type LIKE 'product_variation' AND p.post_parent = $product_id
        AND pm.meta_key LIKE '_stock_status' AND pm.meta_value LIKE 'instock'
    ");

    $count_in_stock = reset($count);
}

// Your condition
if( $count_in_stock <= 1 ){
   // Do something
}      

这两个代码都经过测试并且可以正常工作.

Both codes are tested and work.

这篇关于获得“有货"的数量. Woocommerce中可变产品的产品变体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆