Using WordPress ‘query_loop_block_query_vars’ PHP filter

The ‘query_loop_block_query_vars’ filter allows you to modify the arguments passed to WP_Query for the Query Loop Block.

This enables you to extend the block’s capabilities with additional settings or meta queries not directly supported by the core Query Loop Block.

Keep in mind that this filter will only affect the query rendered on the front-end and not the editor preview. Also, it’s recommended to use attributes compatible with the REST API for identical queries on both sides.

Usage

To use this filter, add the following code to your theme or plugin:

add_filter( 'query_loop_block_query_vars', 'your_function_name', 10, 3 );

Parameters

  • $query (array): An array containing parameters for WP_Query as parsed by the block context.
  • $block (WP_Block): The block instance.
  • $page (int): The current query’s page.

Examples

Limit Posts by Category

add_filter( 'query_loop_block_query_vars', 'limit_posts_by_category', 10, 3 );

function limit_posts_by_category( $query, $block, $page ) {
  // Add a category parameter to the query
  $query['category_name'] = 'news';
  return $query;
}

This code adds a filter to limit the Query Loop Block to display posts only from the “news” category.

Order Posts by Comment Count

add_filter( 'query_loop_block_query_vars', 'order_posts_by_comment_count', 10, 3 );

function order_posts_by_comment_count( $query, $block, $page ) {
  // Set orderby parameter to comment_count
  $query['orderby'] = 'comment_count';
  return $query;
}

This code modifies the Query Loop Block to display posts ordered by the number of comments they have.

Exclude Posts with Specific Tags

add_filter( 'query_loop_block_query_vars', 'exclude_posts_with_tags', 10, 3 );

function exclude_posts_with_tags( $query, $block, $page ) {
  // Exclude posts with specific tags
  $query['tag__not_in'] = array( 3, 4 );
  return $query;
}

This code excludes posts with tags that have the IDs 3 and 4 from the Query Loop Block.

Display Posts from Specific Author

add_filter( 'query_loop_block_query_vars', 'display_posts_from_author', 10, 3 );

function display_posts_from_author( $query, $block, $page ) {
  // Set the author parameter to a specific author ID
  $query['author'] = 1;
  return $query;
}

This code modifies the Query Loop Block to display posts only from the author with the ID of 1.

Display Posts with Custom Field Value

add_filter( 'query_loop_block_query_vars', 'display_posts_with_custom_field', 10, 3 );
function display_posts_with_custom_field( $query, $block, $page ) {
// Add a meta query to filter posts by a custom field value
$query['meta_query'] = array(
array(
'key' => 'featured',
'value' => '1',
'compare' => '=',
),
);
return $query;
}

This code adds a meta query to the Query Loop Block, displaying only posts with a custom field named “featured” and a value of “1”.