Change arguments of the global query

Problem: We have default WordPress pages where not obviously set arguments e.g. archive.php how reset or change them?

How to change arguments of the global query on default pages

Solution: Next we should use this code:

add_action( 'pre_get_posts', 'custom_query_on_archive_page' );
	
function custom_query_on_archive_page( $query ) {
    // Check Post Type
	if ( $query->is_post_type_archive( 'news' ) && $query->is_main_query() && ! is_admin() ) {
		$query->set( 'posts_per_page', 10 );
	} else if ( $query->is_post_type_archive( 'events' ) && $query->is_main_query() && ! is_admin() ) {
		$args = [
			'post_type' => 'events',
			'posts_per_page' => -1,
			'fields' => 'ids',
		];
		
		$events = new WP_Query( $args );
    	$events_ids = $events->posts;
		$exclude_posts_ids = [];
			
		foreach ( $events_ids as $event_id ) {
			if ( strtotime( current_time( 'F j, Y' ) ) > strtotime( get_field( 'start_date', $event_id ) ) ) {
				$exclude_posts_ids[] .= $event_id;
			}
		}
			
		$query->set( 'posts_per_page', 12 );
		$query->set( 'orderby', 'meta_value' );
		$query->set( 'order', 'ASC' );
		$query->set( 'meta_key', 'start_date' );
		$query->set( 'post__not_in', $exclude_posts_ids );
	}
}

Leave Comment

Your email address will not be published. Required fields are marked *