WordPress:统计指定用户所有文章的自定义meta_value总和
Sum Meta Values for a Specific User in WordPress
Got it, let's sort this out for you! Your original code counts how many posts have the _heart_this meta key, but we need to calculate the sum of all the numeric meta values instead. Here are two solid approaches:
Option 1: Efficient Database Query (Recommended)
Using $wpdb directly is the fastest way, since we don't need to load full post objects—we just need an aggregated sum.
global $wpdb; $target_user_id = 1; // The user ID you're targeting $total_heart_sum = $wpdb->get_var( $wpdb->prepare( "SELECT SUM(pm.meta_value) FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID WHERE pm.meta_key = %s AND p.post_author = %d AND p.post_status = 'publish' // Optional: exclude drafts/private posts AND pm.meta_value REGEXP '^[0-9]+$'", // Ensure we only sum numeric values '_heart_this', $target_user_id ) ); // Output the sum, default to 0 if no matching posts exist echo $total_heart_sum ? $total_heart_sum : 0;
Why this works:
- The
INNER JOINensures we only count posts that actually belong to the target user (avoids orphaned postmeta entries). REGEXP '^[0-9]+$'filters out any non-numeric meta values, so you don't get weird results from invalid data.$wpdb->prepare()keeps your query safe from SQL injection—always use this when adding variables to database queries!
Option 2: Using WP_Query (More Intuitive for Beginners)
If you prefer working with WordPress' native query system, you can loop through matching posts and accumulate the values:
$user_posts = new WP_Query([ 'meta_key' => '_heart_this', 'author' => 1, 'posts_per_page' => -1, // Fetch all matching posts 'post_status' => 'publish' // Optional: limit to published posts ]); $total_heart_sum = 0; if ($user_posts->have_posts()) { while ($user_posts->have_posts()) { $user_posts->the_post(); $heart_value = get_post_meta(get_the_ID(), '_heart_this', true); // Only add to the sum if the value is a number if (is_numeric($heart_value)) { $total_heart_sum += intval($heart_value); } } wp_reset_postdata(); // Critical: reset the global post data after the loop } echo $total_heart_sum;
Note on performance:
This method is fine for small post counts, but if the user has hundreds or thousands of posts, the direct $wpdb query will be much faster since it avoids loading all post objects into memory.
内容的提问来源于stack exchange,提问作者robert0
相关产品推荐
相关产品推荐

