user3256143 user3256143 - 1 year ago 87
PHP Question

Count posts with meta value

I'm trying to show the number of posts that have certain

meta key
for the current user.

This is my code:

$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
'post_status' => 'publish',
'author' => $current_user_id,
'meta_query' => array(
'key' => 'color',
'value' => array('red', 'blue')
$posts_array = get_posts( $args );
$the_count = count($posts_array);

echo $the_count;

Thi is counting ALL posts for the current user, ignoring the
meta key

I only need the
to be the number of posts that have a
meta key
for the current user.

What am I doing wrong?

Thanks in advance!

Answer Source

I am not sure, but you could try something like this:

$args = array(
    'posts_per_page'    => -1,
    'post_type'         => 'post',
    'post_status'       => 'publish',
    'author'            => $current_user_id,
    'meta_key'          => 'color',
    'meta_value'        => array('red', 'blue')

$posts_query = new WP_Query($args);
$the_count = $posts_query->post_count;

echo $the_count;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download