Current Single Post Reference From Inside a Bricks Query Loop

Updated on 16 May 2024

When working on advanced customizations in Bricks, sometimes it is necessary to get a handle of the current single post (of any post type) in which a query loop is present from inside the query loop.

Sample use case: Get the single post’s custom field (like ACF Repeater or Meta Box Group) array row corresponding to the loop’s counter/index. An application of this will be shared in another detailed tutorial.

This Pro tutorial covers 3 ways of going about this.

Method 1

<?php

echo get_queried_object_id();

?>

Method 2

<?php

echo BricksDatabase::$page_data['preview_or_post_id'];

?>

Method 3

<?php

echo BricksDatabase::$page_data['original_post_id'];

?>

Example 1 – Getting the host post’s title

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

<?php 

function bl_get_host_post_title(): string {
    return get_queried_object()->post_title;
}

Whitelist the bl_get_host_post_title function.

Ex.:

<?php 

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

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

More info on whitelisting can be found here.

Now the function can be used like this:

{echo:bl_get_host_post_title}