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.

I want to filter posts in such a way that only posts, for which get_post_meta($post->ID, "project_cat", true) (it returns a post ID) is equal to my specified value, are shown.

Any way to do this?

I am especially interested in ways to do it compatible with WP-Paginate plugin.

share|improve this question
    
56% is pretty low - please remember to return to your old questions and accept correct answers. It takes them off the 'unanswered' pile and helps others find solutions more easily. People will also be more willing to offer answers if they know that the OP will respond to them. :) –  Stephen Harris Apr 10 '12 at 15:58
    
See my answer below. It's not clear when/where you want to filter the posts. If you update your answer to include this I can suggest which 'conditionals' you need to check. Alternatively, see the linked query_post example. The general principle is the same - setting the meta_query value. –  Stephen Harris Apr 10 '12 at 16:24
add comment

1 Answer 1

up vote 4 down vote accepted

The WP_Query object accepts a post meta argument. Generally speaking you want to do the following:

  $my_query = new WP_Query( 
    array(
      'post_type' => 'post',
      'meta_query' => array(
        array(
          'key' => 'project_cat',
          'value' => 'my-value',
        )
      ),

        // Other query properties
    ) 
  );

Where 'my-value' is your 'specified value'.

Example usage:

  add_action( 'pre_get_posts' , 'my_pre_get_posts' );

  function my_pre_get_posts( $query ) {

    // Check this is main query and other conditionals as needed
    if( $query->is_main_query() ) {
        $query->set( 
          'meta_query', 
          array( 
            array(
              'key' => 'project_cat',
              'value' => 'my-value'
            )
          )
        );
    }

  }

See WP_Query, pre_get_posts. All conditionals are available to you. Currently this runs on every main query - which you probably don't want.

Alternatively you can use query_posts (a simpler, but much less efficient way) to alter the query for only a specific instance in a template.

share|improve this answer
    
@TahirYasin - see the codex. –  Stephen Harris Sep 12 '13 at 8:50
add comment

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.