I need to exclude posts that have a custom field 'city' value of 'Melbourne'.

After much searching I think the solution might consist of 2 parts.

In functions.php : A function to get the post IDs for all posts which have a custom field 'city' value of 'Melbourne'.

Then in my loop : Exclude these posts using the post_not_in argument, using the returned ids from the first loop?

Is this the right approach? What is the correct code?

  • 2
    What have you tried? Please edit your question to include your current code attempts. – Chip Bennett Nov 14 '13 at 14:03

You can use meta query in wp query to get required posts

  $args = array(
   'meta_query' => array(
     'relation' => 'OR',
        'key' => 'city',
        'value' => 'Melbourne',
        'compare' => 'NOT LIKE'
        'key' => 'city',
        'value' => 'Melbourne',
        'compare' => 'NOT EXISTS'
  $query = new WP_Query( $args );

I think getting ALL the posts with the city = Melbourne and then checking ALL of them against ALL the posts that you are attempting to show on the page is the wrong way about it.

Why not use the single loop that you should already have and put something like this to check if the city is Melbourne?

    //check custom field 'city'
    $custom_field = get_post_custom();              
    if(isset($custom_field["city"][0]) && $custom_field["city"][0] != 'Melbourne')
        //do something else?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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