0

I added post_meta 'batch' to 'assignment' custom post as follows:

update_post_meta( $id, 'batch', strip_tags($_POST['batch']));

Now I am trying to retrieve this data as follows:

$args = array(
    'post_type'   => 'assignment',
    'post_status' => 'publish',
);

$assignments = new WP_Query( $args );

I want to get all data having 'batch=2017'. How can I do this?

2

Change your WP Query arguments like this:

$args = array(
    'post_type'   => 'assignment',
    'post_status' => 'publish',
    'meta_key'     => 'batch',
    'meta_value'   => '2017',
);

For multiple post meta you can use meta_query like this

$args = array(
    'post_type'   => 'assignment',
    'post_status' => 'publish',
    'meta_query' => array(
        array(
            'key'     => 'color',
            'value'   => 'blue',
        ),
        array(
            'key' => 'year',
            'value' => '2017',
        )
    ),
);
|improve this answer|||||
  • If I want to set multiple meta_key and value, how can I do this?. i.e: I want to get data of batch='2017' and 'dept=EEE' and 'section=A' – Abdus Sattar Bhuiyan Dec 12 '17 at 14:20
  • 1
    Use meta_query argument like this: 'meta_query' => array( array( 'key' => 'color', 'value' => 'blue', ), array( 'key' => 'year', 'value' => '2017', ) ), – hamdirizal Dec 12 '17 at 14:29
  • @hamdirizal You should edit your answer to reflect the comment for multiples. – Nathan Powell Dec 12 '17 at 14:42
  • Use relation => 'AND' inside meta_query array. Here is a sample screenshot taken from codex: i.gyazo.com/5f903509f342b1c974227eba1b5314bc.png – Saikat Dec 15 '17 at 16:26
2

First of all, creating a custom taxonomy named "batch" and creating required terms with it would have made this very easy.

$args = array(
    'post_type'   => 'assignment',
    'post_status' => 'publish',
);

$assignments = new WP_Query( $args );

if ( $assignments->have_posts() ) {

    while ( $assignments->have_posts() ) {
            $assignments->the_post();
           $batch = get_post_meta( get_the_ID(), 'batch', true );
           if($batch == 2017){
              echo get_the_title();
           }
    }

}
|improve this answer|||||

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.