I need to sum custom field values of a custom post type with a particular taxonomy ONLY.
For example…
- Custom Post Type: Computers
- Taxonomy: Laptops
- Custom Field: Quantity
How can I get the quantity value of “laptop” “computers” only?
I have been using the following to sum custom fields of ALL taxonomies… can it be modified to restrict to certain taxonomies?
$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 );
Also just tried this as suggested and get a value of 0 returned..
$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 );
You would have to
JOIN
a couple of tables.I am fairly sure that is right. These things are complicated.
If your
meta_value
is a number– that is, no punctuation or other spaces– you should be able to useSUM(meta_value)
and avoid thearray_sum
after the fact.I couldn’t get the SQL statements to work so I came up with another approach (not the best way to do this, but it works)…