User_FTW
User_FTW

Reputation: 524

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!

Upvotes: 1

Views: 4089

Answers (2)

Cici
Cici

Reputation: 1

If you want to use the meta_query array, you have to put the meta_key and meta_value in a subarray:

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

This is because you can use multiple meta_key to combine them.

    'meta_query'        => array(
        'relation' => 'AND',
        array(
           'key'        => 'color',
           'value'      => array('red', 'blue'),
        ),
        array(
           'key'        => 'size',
           'value'      => array('l', 'xl', 'xxl'),
        ),
    ),

Upvotes: 0

LoicTheAztec
LoicTheAztec

Reputation: 253939

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;

Upvotes: 4

Related Questions