pre_get_posts filter using numeric meta_query comparison (from dates)

As mentioned in the comments you an issue in your meta query, as you set the key to 20161126 or similar. Instead key should be filled with your meta key post_end_date. Meta query also support multiple arrays to combine your query to also include posts where the meta key is not set. The example would be something like the following:

function expiry_filter($query) {
  if( !is_admin() && $query->is_main_query() ) {
    $expire = get_field('post_end_date') ? : date('Ymd');
    $query->set( 'meta_query', [
      'relation' => 'OR',
      [
       'key'     => 'post_end_date',
       'value'   => $expire,
       'compare' => '>=',
       'type'    => 'NUMERIC',
      ],
      [
       'key'     => 'post_end_date',
       'compare' => 'NOT EXISTS',
      ],
    ]);
  }
}
add_action( 'pre_get_posts', 'expiry_filter' );

Leave a Comment