exclude custom post type by meta key in wp_query

I’m trying to display a custom post type (properties) and exclude posts that have a certain meta value (sold). Is there a way that I can do this? I have this for my code so far:

                        $args = array(
                            'post_type'      => 'property',
                            'orderby'        => 'meta_value',
                            'meta_key'       => 'random_775',
                            'order'          => 'ASC',
                            'posts_per_page' => 100,
                        );

                    $the_query = new WP_Query( $args ); ?>
                    <?php if ( $the_query->have_posts() ) : ?>
                    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

So right now it shows all the custom post types even the ones that are ‘sold’. How can I show the ones that are not sold? Also, sold is just a checkbox so it would have to know whether it was checked or not.

Suggestions? Thanks!

1 Answer
1

If you don’t use any other meta data, just add the following to your $args:

'meta_key' => 'sold',
'meta_value' => true, // or whatever it is you're using here
'meta_compare' => '!=',

Otherwise, use a WP_Meta_Query:

'meta_query' => array(
    array(
        'key' => 'sold',
        'value' => true,  // or whatever it is you're using here
        'compare' => 'NOT LIKE',
    ),
),

See here for more information:

  • WP_Query
  • WP_Meta_Query

Leave a Comment