I am running a competition which is based on WP Custom Fields. I am trying to count all meta values of a meta_key=’odd’ for a specific user. I am using the formula below but it’s not returning any result.
$meta_key = 'odd';
$post_author = 'Admin';
$odd = $wpdb->get_var( $wpdb->prepare(
"
SELECT Count(meta_value)
FROM $wpdb->postmeta
INNER JOIN $wpdb->posts ON $wpdb->postmeta->post_id = $wpdb->posts->ID
WHERE $wpdb->postmeta->meta_key = 'odd' AND $wpdb->posts->post_author = 'Admin'
",
$meta_key, $post_author
) );
echo "<p>Total odd {$odd}</p>";
Anyone can help me? Thanks in advance.
You are mixing up the
$wpdbvariables and the$postvariables – for yourJOIN, for example, you can’t use$wpdb->postmeta->post_id, it would be{$wpdb->postmeta}.post_id, and would be even better to just use table aliases. Yourprepare()is also not passing in yourmeta_keyorauthorbecause you don’t have%splaceholders for them