我有一个类别为Nexus 4的类别:lg-nexus-4-e960
在这个类别中,我有100个帖子。在wp_postmeta表中,这些帖子中的每一个都有meta_field = sales_count和meta_value = 1或更大。
我想在自定义模板的循环之外回显该类别组合的所有sales_count的总价值。本质上是获得销售量。
我对它可能如何工作有一些想法,但是我不知道如何实现它。查询wp_postmeta表,其中保存了自定义字段,并使用sum()sql函数?
我尝试了这段代码,但是缺少类别规范:
<?php
$meta_key = 'sales_count';//set this to your custom field meta key
$allmiles=$wpdb->get_var($wpdb->prepare("SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
echo '<p>Total miles is '.$allmiles . '</p>';
?>
也许不是最优雅的解决方案
<?php
$catPost = get_posts(array('category' => get_cat_id("yourCategory"))); //change this
foreach ($catPost as $post) {
setup_postdata($post);
$ids[] = get_the_ID();
}
//we now have an array of ids from that category, so then
$idList = implode(",", $ids); //turn the array into a comma delimited list
$meta_key = 'sales_count';//set this to your custom field meta key
$allmiles = $wpdb->get_var($wpdb->prepare("
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
AND post_id in (" . $idList . ")", $meta_key));
echo '<p>Total miles is ' . $allmiles . '</p>';
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句