Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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');
share|improve this question
    
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

2 Answers 2

up vote 8 down vote accepted

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.

share|improve this answer
    
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
    ";
share|improve this answer
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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