Using WordPress ‘build_query_vars_from_query_block()’ PHP function

The build_query_vars_from_query_block() WordPress PHP function is a helper function that constructs a WP_Query args array from a Query block properties. It’s mainly used in Query Loop, Query Pagination Numbers, and Query Pagination Next blocks.

Usage

$block = // Some block instance
$page = 2; // Current page number
$query_vars = build_query_vars_from_query_block($block, $page);

In this example, $query_vars will hold the WP_Query arguments generated from the $block instance for the 2nd page of the current query.

Parameters

  • $block (WP_Block, Required): The Block instance from which WP_Query args need to be generated.
  • $page (int, Required): The current page of the query.

More information

See WordPress Developer Resources: build_query_vars_from_query_block()
Make sure to use this function with the correct blocks (Query Loop, Query Pagination Numbers, Query Pagination Next blocks).

Examples

Using in a Custom Loop

Here, we use the build_query_vars_from_query_block() function to build a custom WP_Query.

// Assume we have a $block instance for a Query block
$page = 2; // We want the second page

$query_args = build_query_vars_from_query_block($block, $page);

$custom_query = new WP_Query($query_args);

while ($custom_query->have_posts()) {
    $custom_query->the_post();
    // Display the post
    the_title();
}

This code creates a new WP_Query using the arguments generated by the function from the given block instance and page number. Then it loops through the posts and displays their titles.

Checking the Generated Args

// Assume we have a $block instance for a Query block
$page = 1; // We want the first page

$query_args = build_query_vars_from_query_block($block, $page);

echo '<pre>';
print_r($query_args);
echo '</pre>';

This example generates the query arguments from a given block instance and then prints them in a human-readable format.