Bricks single mode – Limiting the number of posts to 1 in the editor

Updated on 5 Mar 2024

As of Bricks 1.9.6.1, there is no “single” mode in Bricks query loops like there is in Oxygen – meaning it is not possible to specify that only one post be rendered in the editor for performance reasons esp. when there are many query loops in the page/template.

We can work around this using a corresponding Bricks filter, depending on the query loop type.

Let’s take a standard post query loop. Here’s how you can have it output 6 posts on the front end but only 1 in the Bricks editor.

Step 1

Set posts per page for your query loop in the PHP editor to your desired number, in this case, 6.

return [
    'post_type' => 'post', // not really needed for 'post' post type
    'posts_per_page' => 6,
    'no_found_rows' => true,
];

The reason for not setting this in the “Posts per page” control is because, in 99% of the cases, pagination is not needed for custom query loops, and when pagination is not required, we should set no_found_rows to true to reduce the query load. When PHP query editor is used for this purpose, the value set in the “Posts per page” control will no longer apply and it must also be set in the PHP query editor.

Step 2

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php 

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
    if ( $element_id === 'hrzzby' && bricks_is_builder_call() ) {
        $query_vars['posts_per_page'] = 1;
    }

    return $query_vars;
}, 10, 3 );

Replace hrzzby with the Bricks ID of the query loop-enabled element.

Front end:

After reloading the editor:

For multiple post query loops

<?php 

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
    if ( in_array( $element_id, [ 'hrzzby', 'ddycxn' ] ) && bricks_is_builder_call() ) {
        $query_vars['posts_per_page'] = 1;
    }

    return $query_vars;
}, 10, 3 );

where hrzzby and ddycxn are the Bricks IDs.

For all post query loops

<?php 

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
    if ( bricks_is_builder_call() ) {
        $query_vars['posts_per_page'] = 1;
    }

    return $query_vars;
}, 10, 3 );

For query types like ACF/Meta Box Repeater/Relationship you’d use the bricks/query/result filter. Example.

Note: We have not tested how much of a performance gain this will bring in reality. But something worth trying, if you are currently affected by the problem.

Instant access to 390+ Bricks code tutorials with BricksLabs Pro

Leave the first comment