Alternating Posts from Two Post Types in Bricks

This Pro tutorial provides the steps to output posts from two post types (could be the built-in ones or CPTs) in an alternating manner in a Bricks query loop.

Step 1

In the Bricks editor, enable query loop on a Block.

Click the query icon and enable PHP query editor.

Paste:

// Get posts from the first CPT
$args1 = array(
  'post_type' => 'post',
  'posts_per_page' => -1, // Get all posts
  'fields' => 'ids' // Only get post IDs
);
$posts1 = get_posts( $args1 );

// Get posts from the second CPT
$args2 = array(
  'post_type' => 'page',
  'posts_per_page' => -1, // Get all posts
  'fields' => 'ids' // Only get post IDs
);
$posts2 = get_posts( $args2 );

// Initialize the result array
$result = [];

// Get the maximum count of posts to iterate
$max_count = max( count( $posts1 ), count( $posts2 ) );

// Merge post IDs alternately
for ( $i = 0; $i < $max_count; $i++ ) {
  if ( isset( $posts1[$i] ) ) {
    $result[] = $posts1[$i];
  }
  if ( isset( $posts2[$i] ) ) {
    $result[] = $posts2[$i];
  }
}

if ( $result ) {
  return [
    'post_type' => [ 'post', 'page' ],
    'posts_per_page' => -1,
    'post__in' => $result,
    'orderby' => 'post__in',
  ];
} else {
  return [
    'post__in' => [ 0 ],
  ];
}

Set your post types in these lines:

'post_type' => 'post',

and

'post_type' => 'page',

and

'post_type' => [ 'post', 'page' ],

Step 2

Add a dynamic data condition on the parent Section to ensure that the entire Section gets output only if there’s at least 1 result.

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

Step 3

Add the linked post title and any other desired elements inside the Block.

Credit

ChatGPT.