我只需要将自定义post类型的自定义字段值与特定分类法相加。
例如
自定义贴子类型:计算机分类:笔记本电脑自定义字段:数量如何仅获取“笔记本电脑”的数量值?我一直在使用以下方法来汇总所有分类法的自定义字段。。。它是否可以修改为仅限于某些分类法?
$total_quantity = array();
$meta_key = \'inventory-quantity\'; //custom field meta key
$total_quantity = $wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
echo \'QTY \'.array_sum( $total_quantity );
也只是按照建议尝试了一下,得到了返回的值0。。
$total_puppies = array();
$meta_key = \'wpcf-litter-puppies\';//set this to your custom field meta key
$total_puppies = $wpdb->get_col($wpdb->prepare
("SELECT meta_value FROM wp_postmeta as pm
INNER JOIN wp_term_relationships as tr ON (pm.post_id = tr.object_id)
INNER JOIN wp_term_taxonomy as tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
WHERE 1
AND tt.taxonomy = \'litter-type\'
AND pm.meta_key = %s",
$meta_key));
echo \'Total Puppies \'.array_sum( $total_puppies );
SO网友:mcseay
我无法让SQL语句工作,所以我想出了另一种方法(这不是最好的方法,但它可以工作)。。。
<?php
$args = array(
\'post_type\' => \'puppies\',
\'taxonomy\' => \'litter-type\',
\'term\' => \'previous-litters\',
\'posts_per_page\' =>-1
);
$loop = new WP_Query($args);
if ( $loop->have_posts() ) : ?>
<?php
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $amt = get_post_meta($post->ID, \'wpcf-litter-puppies\', true); ?>
<?php if ($amt) {$previous_puppies_total += $amt;}; ?>
echo $total; ?>
<?php endwhile; ?>
<?php echo \'Puppies from previous litters: \'.$previous_puppies_total; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>