0

我有一个 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>';
?>
4

3 回答 3

0

更快的方法:

$allmiles = $wpdb->get_var($wpdb->prepare( 
            "SELECT sum( meta_value )
            FROM $wpdb->postmeta
            WHERE meta_key LIKE %s
            AND post_id
            IN ( 
            SELECT post_id
            FROM $wpdb->term_relationships
            WHERE term_taxonomy_id = %d
            )" , $meta_key , $cat_id ) );
于 2014-02-02T03:29:07.720 回答
0

也许不是最优雅的解决方案

<?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>';
?>
于 2013-10-19T16:34:22.440 回答
0

对于仍在寻找更详细解决方案的任何人,我根据 chiliNUT 的上述答案进行了以下工作 - 基于页面 ID 的条件:

<?php if ( is_page( '123' ) ) { ?>/* change number */
<?php } elseif ( is_page( '321' ) ) { ?> /* change to different number */
<?php

$catPost = get_posts(array('post_type' => 'your_post_type', 'post_status' => array('publish', 'future'),'tax_query' => array(array('taxonomy' => 'your_cpt_categories', 'field' => 'slug', 'terms' => 'your-category-slug')))); //change these to suit your registered custom post type, taxonomies, post status, etc.
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 = 'your_meta_key';//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>';
?>

<?php } else { ?>

<?php the_content(); ?> /* or do other stuff */

<?php } ?>
于 2018-06-26T14:30:08.237 回答