Search code examples
wordpressmeta-query

How to filter last one year custom posts by comparing acf custom field date value


I have to get latest posts from only last 12 months by comparing the acf custom field datepicker value

$args = array( 
  'post_type' => 'news',
  'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
   'meta_query' => array(
array(
    'key' => 'publication_date',
     'after'   => '-365 days',
 ),
 ),
 'orderby' => 'meta_value',
  'order' => 'DESC',
  'hide_empty' => 0,
   'pad_counts' => false, 
 );

Solution

  • You can get the post of last a year by:

    $today = date('Ymd'); // Today's date
    $date = strtotime($today.' -1 year'); // converting into string and doing minus a year
    $lastyear = date('Ymd', $date); //get the date of the last year
    
    $args = array( 
      'post_type' => 'news',
      'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
      'orderby' => 'meta_value',
      'order' => 'DESC',
      'hide_empty' => 0,
      'pad_counts' => false,
    
        'meta_query' => array(
          'relation' => 'AND',
               array(
                    'key'       => 'publication_date',
                    'compare'   => '<=',
                    'value'     => $today,
                ),
                   array(
                    'key'       => 'publication_date',
                    'compare'   => '>=',
                    'value'     => $lastyear,
                )
          )
    
     );
    

    Here we can fetch it using meta query.