Get the count of “in stock” product variations for a variable product in Woocommerce

青春壹個敷衍的年華 提交于 2019-12-03 21:38:28

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

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) 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.

Wed

This is my Final working code, achieved with the help of LoicTheAztec answer:

add_action( 'woocommerce_before_single_product', 'my_remove_variation_price' );
function my_remove_variation_price() {
    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++;
        }   
    }

    if( $count_in_stock <= 1 ) 
    {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
    }   

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!