客户希望显示他们在商店中拥有的产品总数,我已经使用了此代码
$numposts = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'product' AND post_status = 'publish'");
哪个工作正常,但它显示已发布产品的总数,我希望它只显示库存在1或更高的位置,所以基本上它只显示实际库存的产品总数
答案 0 :(得分:1)
尝试使用meta_value为'instock'的_stock_status
meta_key加入post_meta表。建议缓存数据,因为您不希望在每个请求上运行此数据,但需要平衡适当的时间来缓存数据(因为缓存期内的销售不会反映在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";