2

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

6

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:

3
  • Thanks, that worked but I no longer have the posts in alphabetical order. Meta_key -> 'random_775' was what was doing it but now that I have two meta_keys, it broke. Any suggestion on how to keep the order? Sep 26, 2013 at 23:29
  • Hm, that's why I wrote the second part using a WP_Meta_Query. So this doesn't work either? Keep the meta_key and orderby parameters from your original code, and add the meta_query. If this is not working, I will post another solution (which uses standard sorting of PHP).
    – tfrommen
    Sep 27, 2013 at 7:07
  • Thanks for the help, but I have another question where I'm using pre_get_posts but I still am having issues. link Sep 27, 2013 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.