Alter query args on the WordPress Query block

I was recently working on a project which utilised the WordPress Query Block in order to display jobs from a custom post type in WordPress.

The custom post type in question was the job_listing post type provided by the WP Job Manager plugin.

It registered a custom post status to assign to jobs called expired. This is assigned to a job when it passes it expiration date, sent as a meta field.

I noticed the output of the Query Block was outputting expired jobs and therefore wanted a way to prevent this happening.

It turns out there is a filter you can use to filter the query parameters used by the Query Block called query_loop_block_query_vars

Here is an example of how to ensured that only published jobs where displayed when a query block was used and the post type was querying job_listing posts.

<?php
/**
 * Alters the query loop query args if the post type is a job listing.
 * Ensures that the query loop block only shows published jobs.
 *
 * @param array $query The query args.
 * @return array $query The query args.
 */
function hd_edit_job_query_loop_block_params( $query ) {

	// if this block is not the jobs post type.
	if ( 'job_listing' !== $query['post_type'] ) {
		// return the query params.
		return $query;
	}
	
	// set post status.
	$query['post_status'] = 'publish';

	// return the query params.
	return $query;

}

add_filter( 'query_loop_block_query_vars', 'hd_edit_job_query_loop_block_params', 10, 1 );