6 Random Posts from Tag A + 6 Random Posts from Tag B in a Single Bricks Query Loop

A user asks:

Hello!

In a query loop, I need to output 12 random posts. 6 with the 1001 tag and 6 with the 1002 tag. Any suggestions on how to achieve that before I fire up VS code?

This Pro tutorial shows how this can be done in a Bricks query loop.

Step 1

Let’s first define a custom function takes in the tag name string and an optional number of posts (with a default of 6) integer as arguments and returns an array of the IDs of x number of posts in the specified tag.

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

<?php 

function bl_get_random_post_ids_by_tag( string $tag, int $count = 6 ): array {
    $args = [
        'post_type'      => 'post',
        'posts_per_page' => $count,
        'no_found_rows'  => true,
        'orderby'        => 'rand',
        'fields'         => 'ids',
        'tax_query'      => [
            [
                'taxonomy' => 'post_tag',
                'field'    => 'name',
                'terms'    => $tag,
            ],
        ],
    ];

    $query = new WP_Query( $args );
    
    return $query->posts;
}

Step 2

Whitelist the bl_get_random_post_ids_by_tag function.

Ex.:

<?php 

add_filter( 'bricks/code/echo_function_names', function() {
  return [
    'bl_get_random_post_ids_by_tag'
  ];
} );

You should also add other functions (native or custom) being used in your Bricks instance besides bl_get_random_post_ids_by_tag. This can be checked at Bricks → Settings → Custom code by clicking the Code review button.

More info on whitelisting can be found here.

Step 3

Edit a Page or template where you would like to show the posts with Bricks.

Set up a query loop on a Block.

Click the query icon and paste this in the PHP editor:

$post_ids_a = bl_get_random_post_ids_by_tag( 'Tag A' );

$post_ids_b = bl_get_random_post_ids_by_tag( 'Tag B' );

$post_ids = array_merge( $post_ids_a, $post_ids_b );

if ( $post_ids ) {
  return [
    'post_type' => 'post',
    'posts_per_page' => -1,
    'post__in' => $post_ids,
    'orderby' => 'post__in',
    'bricks_force_run' => true // disable reuse of query results
  ];
} else {
  return [
    'post__in' => [ 0 ],
  ];
}

Replace Tag A and Tag B with the names of your tags.

Step 4

Select the parent Section of the Block and apply a dynamic data condition so it gets rendered on the front end only if there is at least one matching post.

Replace joyfhd with the Bricks ID of your query-loop enabled Block.