【问题标题】:Woocommerce - Showing only products in stockWoocommerce - 仅显示库存产品
【发布时间】:2014-06-18 05:33:16
【问题描述】:

一个客户想要显示他们商店里的产品总数量,我使用了这个代码

$numposts = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'product' AND post_status = 'publish'");

这很好用,但是它显示了已发布产品的总数,我希望它只显示库存为 1 或更大的位置,所以基本上它只显示实际库存的产品总数

【问题讨论】:

  • 要计算所有库存产品,您必须加入其他表 wp_postmeta 与字段 _sale_price 大于 0
  • 对不起,你需要像个孩子一样跟我说话,我该怎么做?
  • 试试这个SELECT COUNT(*) FROM $wpdb->posts p INNER JOIN $wpdb->postmeta pm ON p.id = pm.post_id WHERE p.post_type = 'product' AND p.post_status = 'publish' AND pm.meta_key = "_sale_price" AND pm.meta_value > 0
  • 没有失败,它把 _sale_price 称为错误,我不确定这是否正确,我不想与销售价格有任何关系我想要任何库存数量为 1 的产品或更多不是销售价格

标签: wordpress woocommerce


【解决方案1】:

尝试使用_stock_status meta_key 加入 post_meta 表,其中 meta_value 为“instock”。建议缓存数据,因为您不想在每个请求上都运行它,但需要平衡适当的时间来缓存数据(因为缓存期内的销售额不会反映在库存商品的总数中)。仅当您使用缓存时才有效(由于查询的数量,强烈建议在 WooCommerce 中使用缓存)。

global $wpdb;
// cache key
$key = 'in_stock_products';
// we get back 'false' if there is nothing in the cache, otherwise 0+
$in_stock_products = wp_cache_get( $key );
// run the query if we didn't get it from the cache
if ( false === $in_stock_products ){
    // create the SQL query (HEREDOC format)
    $sql_query = <<<SQL
    SELECT COUNT(p.ID) AS in_stock_products
    FROM {$wpdb->posts} p
    JOIN {$wpdb->postmeta} pm 
        ON p.ID = pm.post_id 
        AND pm.meta_key = '_stock_status' 
        AND pm.meta_value = 'instock'
    WHERE p.post_type = 'product' AND p.post_status = 'publish'
SQL;
    // query the database
    $in_stock_products = (int) $wpdb->get_var( $sql_query );
    // cache the results, choosing an appropriate amount of time to cache results
    $cache_ttl = 0; // 0 is "as long as possible", otherwise cache time in seconds
    wp_cache_add( $key, $in_stock_products, $cache_ttl ); // cache as long as possible
}
// $in_stock_products now has the value either from the cache or the database query.
echo "There are $in_stock_products in stock";

【讨论】:

  • 太棒了!我建议也使用wp_cache_get()wp_cache_add() 作为这个值,这样你就不会在每个请求上运行SQL 查询。
  • 对不起,请原谅我的无知,但你是怎么做到的??
猜你喜欢
  • 1970-01-01
  • 2022-11-17
  • 2018-02-08
  • 2016-05-06
  • 1970-01-01
  • 2018-10-12
  • 2015-12-30
  • 2018-05-17
  • 1970-01-01
相关资源
最近更新 更多