Support

Account

Home Forums Front-end Issues Date format and wp_query Reply To: Date format and wp_query

  • Hey @ana_p

    I see a few problems with your code.
    First of all, you’re using the meta_key and meta_value incorrectly.

    meta_key is the name of the field, in your case ‘training_date’
    meta_value is the value to compare the field to

    Check the WP Meta Query documentation for more details, https://codex.wordpress.org/Class_Reference/WP_Meta_Query

    Finally, I think your approach to compare only the month to the training dates is incorrect because this way you will get trainings of past and future years too.

    So my suggestion is to use start and end dates for the given month and use meta_query with 'BETWEEN'
    To learn more about meta_query, please take a look at this page: https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

    Create start and end dates for the given month like this

    $month      = '02';
    $start_date = date( 'Y' . $month . '01' );
    $end_date   = date( 'Y' . $month . 't' );

    Use those dates to find training dates ‘BETWEEN’ them in a meta_query

    $args  = array(
       'post_type'      => 'job_listing',
       'posts_per_page' => '30',
       'meta_query'     => array(
          array(
             'key'     => 'training_date',
             'value'   => array( $start_date, $end_date ),
             'compare' => 'BETWEEN',
             'type'    => 'DATE'
          )
       )
    );

    I hope this helps.