user3256143 user3256143 - 5 months ago 35
PHP Question

Count posts with meta value

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

meta key
values
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
values
.

I only need the
$the_count
to be the number of posts that have a
meta key
value
'red'
or
'blue'
for the current user.

What am I doing wrong?

Thanks in advance!

Answer

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;
Comments