获取所有“有货"的数量WooCommerce 中的产品 [英] Get the count of all "In stock" products in WooCommerce

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

问题描述

我有一个网站,产品被视为贸易/交易.因此,当有人进行交易(购买产品)时,它就会缺货.

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

显示当前可用产品的剩余数量(基本上有库存)的 PHP 代码段是什么?

What would be the PHP snippet to display the remaining numbers of product currently available (basically In Stock) ?

例如:快点!只有 10 个交易(woocommerce -> 产品)可用!

ex: Hurry Up! Only 10 trades (woocommerce -> products) available!

提前致谢!

我尝试了提供的代码:

function fp2() {
    global $wpdb; 

    $stock = get_post_meta( $post->ID, '_stock', true ); 

    echo '<span style="color:#fff;text-align:center;font-size:12px">Remaining Trade:' . $stock;
}
add_shortcode('fp7', 'fp2');

推荐答案

已更新 (2021)

这是一个带有 SQL 查询的自定义函数,它将返回产品instock";计数:

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);
}

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

经过测试和工作

使用示例 (在任何 php 文件中):

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

将显示如下内容:

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

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