0

I'm trying to count the number of posts where certain meta key values exist, in this case posts that have a key 'texture' with the value 'soft', and also have a key 'colours' that are 'red', 'blue' or 'green'.

My code does not error, but it appears to count all posts instead of just the ones with the meta key values as mentioned:

$args = array(
    'posts_per_page'    => -1,
    'post_type'         => 'post',
    'post_status'       => 'publish',
    'author'            => $current_user_id,
    'meta_query' => array(
       'key'   => 'texture',
       'value' => 'soft'
    ),
    array(
       'key'   => 'colours',
       'value' => array('red', 'blue', 'green')
    )
);

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

echo $the_count;

What am I doing wrong?

Cheers.

User_FTW
  • 504
  • 1
  • 16
  • 44

1 Answers1

1

Try adding 'relationship' => 'AND' in meta_query and 'compare' => 'IN' in meta array that have multiple values ('red', 'blue', 'green') like this :

'meta_query' => array(
    'relationship' => 'AND',
    array(
        'key'   => 'texture',
        'value' => 'soft'
    ),
    array(
        'key'   => 'colours',
        'value' => array('red', 'blue', 'green'),
        'compare' => 'IN'
    )
)

Edit #1:

Maybe adding % mark around your values would solve problem, I'm not 100% sure it would work but you can try it, like this:

'meta_query' => array(
    'relationship' => 'AND',
    array(
        'key'   => 'texture',
        'value' => 'soft'
    ),
    array(
        'key'   => 'colours',
        'value' => array('%red%', '%blue%', '%green%'),
        'compare' => 'IN'
    )
)

I hope it works, Thanks..

Shady Alset
  • 5,548
  • 4
  • 21
  • 34