Get the count of all “In stock” products in WooCommerce

前端 未结 1 735
囚心锁ツ
囚心锁ツ 2021-01-24 09:57

I have a site where products are considered trade/deal. Therefore, when someone take a trade (buy a product), it become out of stock.

What would be the PHP snippet to d

相关标签:
1条回答
  • 2021-01-24 10:21

    Updated (2021)

    Here is a custom function with a SQL query that will return the products "instock" count:

    function get_instock_products_count(){
        global $wpdb;
    
        // The SQL query
        $result = $wpdb->get_var( "
            SELECT COUNT(p.ID)
            FROM {$wpdb->prefix}posts as p
            INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
            WHERE p.post_type LIKE '%product%'
            AND p.post_status = 'publish'
            AND pm.meta_key = '_stock_status'
            AND pm.meta_value = 'instock'
        " );
        
        return reset($result);
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    Tested and working


    Usage example (in any php file):

    $count = get_instock_products_count();
    $message = sprintf( __( 'Hurry Up! Only %s remaining trades' ), $count );
    echo '<div class="woocommerce-message">'.$message.'</div>';
    

    will display something like:

    0 讨论(0)
提交回复
热议问题