Support

Account

Home Forums Front-end Issues Date format and wp_query

Helping

Date format and wp_query

  • Hi,

    I’m new to PHP and WordPress development and just trying to get my hands off a problem I have with ACF.

    I created a custom post type named ‘training’ with a Date field. The return format is YYYYMMDD and I managed to display it the way I want using the DateTime object.

    The problem is that I have an Agenda page template where I want to show all the trainings but only for a month given. For example, I want to display all the trainings which have a date set to February. How can I do that ?

    I tried to do something like this but it doesn’t work:

    <?php
    
        $date = get_field('training_date', false, false);
        $date = new DateTime($date);
        $date->format('m');
    
        $args = array(
            'post_type' => 'training',
            'showposts' => '30',
            'meta_key' => $date,
            'meta_compare' => '=',
            'meta_value' => '02',
            ); 
    
        $query = new WP_Query($args);
    
        while ($query->have_posts()) : $wp_query->the_post();
    
    ?>
    
        <h2><?php the_title(); ?></h2>
        <?php the_field('training_date');?>
    
    <?php endwhile; wp_reset_query(); ?>

    Note sure what I’m doing wrong and which arguments I need to pass in the query… Can you help?

    Thanks!

  • 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.

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Date format and wp_query’ is closed to new replies.