Skip to main content
5 of 5
added 49 characters in body

Selecting posts with a given meta value for a meta key

I'm trying to run a query that returns all the posts with a given value for a specific meta key. I know for a fact that this is none of the posts on my test server but it reports finding all the posts with a post count of 7 (there are 21 posts).

I have been following the notes here and the question here but I cannot get a sensible outcome.

    $args = array(
            'post_type'  => 'post',
            'meta_query' => array(
                'relation' => 'AND',// outcome is the same with and without this line
                array(
                    'key'     => 'perma',
                    'compare' => '=', 
                    'value'   => "{$raw_perma}"
                ),
            ),
        );

    // create a custom query
    $my_query = new \WP_Query( $args );
    
    
    echo $my_query->post_count; // 7 (regardless of $raw_perma value).

I would like to know what I am doing wrong. As "are there posts with this meta key-value pair?" seems like it should be a trivial question to answer.

Update

Found another question and tried this:

    $args = array(
                'posts_per_page'   => -1,
                'post_type'        => 'post',
                'meta_key'         => 'perma',
                'meta_value'       => "{$raw_perma}"
            );

This works although I have no idea why this and not that. Would like to see an explanation in an answer.