Why the ‘date_query’ is not working in ‘pre_get_posts’ hook?

I need to output popular posts in a blog using several params:

  • Not older than one week;
  • Rating is over than 250;
  • Order by date

Here is my code:

function evanre_custom_order_query( $query ) {

  if ( is_admin() || ! $query->is_main_query() ) {
    return;
  }

  $query_var_show = get_query_var( 'show' );

  if ( empty( $query_var_show ) ) {
    return;
  }

  if ( 'popular' === $query_var_show ) {
    $query->set( 'orderby', 'date' );
    $query->set( 'meta_query', array(
      array(
        'key'     => 'blt_upvotes',
        'value'   => 250,
        'compare' => '>=',
        'type'    => 'NUMERIC',
      ),
    ) );
    $query->set( 'date_query ', array(
      array(
        'after' => '1 week ago'
      )
    ) );
  }

}

add_action( 'pre_get_posts', 'evanre_custom_order_query' );

My custom query_var is registered and working. Ordering by date works, meta_query works too. date_query is completely ignored. What am I missing?

1 Answer
1

You’ve got trailing space in your $query->set().

Instead of

$query->set( 'date_query ', ...

it should be:

$query->set( 'date_query', ...

Leave a Comment