Support

Account

Home Forums ACF PRO Get posts if Custom Field Date is GREATER than Today's Date

Solved

Get posts if Custom Field Date is GREATER than Today's Date

  • I have a custom field with the ID of: research_enddate

    If the date of research_enddate is in future of today’s date, then I would like that post to show in my “Related Posts” section on my page. If the date is in the past, then it should not show up.

    Here is what I have so far, but my logic here on dates is not working as intended. Any ideas?

    <?php
    $today = date("F j, Y");  
    // get the custom post type's taxonomy terms
    $custom_taxterms = wp_get_object_terms( $post->ID, 'researchopp_unit', array('fields' => 'ids') );
    // arguments
     $args = array(
     'post_type' => 'researchopp',
     'post_status' => 'publish',
     'posts_per_page' => 3, // you may edit this number
     'orderby' => 'rand',
     'tax_query' => array(
        array(
           'taxonomy' => 'researchopp_unit',
           'field' => 'id',
           'terms' => $custom_taxterms
        )
      ),
    'meta_query' => array(
       array(
         'key' => 'research_enddate',
       ),
       array(
         'key' => 'research_enddate',
         'value' => $today,
         'compare' => '>='
       )
     ),		
     'post__not_in' => array ($post->ID),
     );
     $related_items = new WP_Query( $args );
     // loop over query
     if ($related_items->have_posts()) : ?>
  • 
    $today = date("Ymd");
    
    
    'meta_query' => array(
       array(
         'key' => 'research_enddate',
         'value' => $today,
         'compare' => '>='
       )
     ),
    
  • Ok, so the difference was the fact that I need to be calling the date in Ymd format instead of F j, Y.

    Once I changed that to what you wrote, it appears to working as intended.

    Thanks!

  • yes, when building queries you need to query based on how ACF stores the value in the DB and not how you display the value. ACF stores values for all fields consistently, this way you can alter how the value is returned in the future without needing a major DB update.

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

The topic ‘Get posts if Custom Field Date is GREATER than Today's Date’ is closed to new replies.