How to filter WP_Query for posts having a certain meta-value, without using a Custom Select Query?

I have a custom posttype with meta-key: "open", and meta-value options: "yes" or "no".

I would like to show posts only with meta_value = yes, for meta_key = "open".

function filter_where($where = '') {    

    $open = "yes";

    //$where .= " AND post_date > '" . date('Y-m-d', strtotime('-2 days')) . "'";
    return $where;
add_filter('posts_where', 'filter_where');
  • Are you doing this in a template file? Can you post the full code of your template file then? Is this the main loop of this page? – Jan Fabry Dec 28 '10 at 10:53

I am not sure from your wording if you hadn't tried it with query argument or it didn't work?

$the_query = new WP_Query(array( 'meta_key' => 'open', 'meta_value' => 'yes' ));

Custom Field Parameters in Codex.

  • thanks for your swift reply. I did try that, but for some reason it does not work for me. For, it throws a 404. – Henk Jan Dec 21 '10 at 9:56
  • Where did you place the code? – t31os Dec 21 '10 at 20:34
  • I put it in a $args array after my $paged setting: $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; and before: $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query($args); – Henk Jan Dec 22 '10 at 11:17
  • @Henk Jan please add code to your question, comment are unsuitable for it – Rarst Dec 22 '10 at 11:28
  • my custom post type was not registered properly in the database. After I fixed that, your solution did the trick. Thanks. – Henk Jan Jan 19 '11 at 11:22
 $querystr = "
    SELECT wposts.* 
    FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    WHERE wposts.ID = wpostmeta.post_id 
    AND wpostmeta.meta_key = 'custom-key' 
    AND wposts.post_type = 'page' 
    ORDER BY wpostmeta.meta_value DESC
  • 2
    An explanation would tell us why this is an answer. – Brian Fegter Oct 8 '12 at 19:53
  • Double that. Also: Use the $wpdb methods when doing queries. – kaiser Oct 8 '12 at 22:08

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.