I have a custom field called "points." I want to count up all of the points values for all of the posts which contain that custom field and who also have a specific post title.
This is what I have so far, but I am having trouble figuring out how to add the parameters since it needs to come from two different tables in the database:
<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'cf_PointValue';
$total_points = $wpdb->get_var( $wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$meta_key
) );
echo "<p>Total points: {$total_points}</p>";
?>
I assume there needs to be something added to join it with the other tables. What I want it do do is something like this:
<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'cf_PointValue';
$total_points = $wpdb->get_var( $wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
WHERE post_title = 'name a specific post'
WHERE wp_terms = 'tag1'
",
$meta_key
) );
echo "<p>Total points: {$total_points}</p>";
?>
Thanks in advance for any help you can provide!
This postmeta thing is a key-value table, and takes some special monkey business to use. It takes a special JOIN operation. You need a query like this:
SELECT SUM(m.meta_value) AS points
FROM $wpdb->posts p
JOIN $wpdb->postmeta m ON p.id = m.post_id AND m.meta_key = %s
WHERE p.post_title = 'name a specific post'
AND p.post_status = 'publish'
See the two items in the JOIN of postmeta? The first one picks up the appropriate post id, and the second chooses postmeta rows with the correct meta_key value for what you're trying to sum up.