Home Javascript Modify the WP_Query with pre_get_posts()

Modify the WP_Query with pre_get_posts()

by Ker

Custom Query is the right tool when you want to do something that isn’t related to the current URL. But when we want to work with the default URL base query, it is recommended to use pre_get_posts() to modify the query setting before the main query run. We place the pre_get_posts() in functions.php.

For example, we want to show a list of events custom post type in an event archive page. First, we use add_action to register the pre_get_posts() function. Then we check the following conditions:

  • Make sure we are not modifying the admin dashboard
  • Make sure we work with the correct custom post type
  • Make sure we only access the main query without affecting other custom queries

function event_archive($query) {
    if(!is_admin() && $query->is_main_query() && is_post_type_archive('event')){
        $query->set('meta_key', 'event_date');
        $query->set('meta_query', [[
          'key'     => 'event_date',
          'compare' => '>=',
          'value'   => date('Ymd'),
          'type'    => 'NUMERIC']])
         $query->set('orderby', 'meta_value_num'),
         $query->set('order', 'ASC')

add_action('pre_get_posts', 'event_archive');

Reference: https://www.billerickson.net/customize-the-wordpress-query/

Related Videos

Leave a Comment