Customize WordPress Default Query
1 min readSep 30, 2020
How to customize the default query on the archive page for a event custom post?
Change the order of custom posts on the event archive page
Add the following code snippet on the functions.php file
function adjust_queries($query) {
if (!is_admin() AND is_post_type_archive('event') AND $query->is_main_query()) {
$query->set('meta_key', 'event_date');
$query->set('orderby', 'meta_value_num');
$query->set('order', 'ASC');
$query->set('meta_query', array(
array(
'key' => 'event_date',
'compare' => '>=',
'value' => new Date('Ymd'),
'type' => 'numeric'
)
))
}
}add_action('pre_get_posts', 'adjust_queries');
Show only past events
Create a new custom query
$pastEvents = new WP_Query(array(
'post_type' => 'event'
'meta-key'=> 'event_date'
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query => array(
array(
'key' => 'event_date',
'compare' => '<',
'value' => new Date('Ymd'),
'type' => numeric
)
)
));while($pastEvents->have_posts()) {
$pastEvents->the_post();
}
Default pagination function will not work if you are using custom queries. You also need to make small changes to the pagination function.
In default query, pagination can be added with the following code.
echo paginate_links(array());
In custom query, make changes to the pagination function like the following.
echo paginate_links(array(
'total' => $pastEvents->max_num_pages
));
We also need to add one parameter to the custom WP_Query to make the pagination work.
paged =>
$pastEvents = new WP_Query(array(
'paged => get_query_var('paged', 1),
'post_per_page' => 2,
'post_type' => 'event'
'meta-key'=> 'event_date'
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query => array(
array(
'key' => 'event_date',
'compare' => '<',
'value' => new Date('Ymd'),
'type' => numeric
)
)
));while($pastEvents->have_posts()) {
$pastEvents->the_post();
}