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 Answers 2

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',
        )
    ),
);
4
  • 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' Commented Dec 12, 2017 at 14:20
  • 1
    Use meta_query argument like this: 'meta_query' => array( array( 'key' => 'color', 'value' => 'blue', ), array( 'key' => 'year', 'value' => '2017', ) ),
    – hamdirizal
    Commented Dec 12, 2017 at 14:29
  • @hamdirizal You should edit your answer to reflect the comment for multiples. Commented Dec 12, 2017 at 14:42
  • Use relation => 'AND' inside meta_query array. Here is a sample screenshot taken from codex: i.gyazo.com/5f903509f342b1c974227eba1b5314bc.png
    – Saikat
    Commented Dec 15, 2017 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();
           }
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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