php – Replace block content with an array
I’m using GenerateBlocks and Metabox, and specifically relevant for this post, MB Relationships.
I have a query loop created with GenerateBlocks that displays a list of Events (CPT). I have another CPT called Licensees, and with MB Relationships I have created a ‘Relationship’ between these 2 CPTs.
My goal is to insert content from the ‘related’ Post, i.e. I want to display the name of the related Post in each object of the query loop. Here is the code I’m using:
add_filter( 'render_block', function( $block_content, $block ) {
if ( !is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'licensee-name' ) !== false ) {
$myreplace1 = 'placeholder';
$hol_licensee_name = MB_Relationships_API::get_connected( [
'id' => 'licensee-events',
'to' => get_the_ID(),
] );
$block_content = str_replace( $myreplace1, $hol_licensee_name , $block_content );
}
return $block_content;
}, 10, 2 );
I have tested this code snippet with a flat value, e.g. ‘Test value’, and it works. So I know the function fundamentally works.
However the script doesn’t work (= breaks the query loop entirely). I believe the offending part is where I define $hol_licensee_name
.
I was told by Metabox support that
The function MB_Relationships_API::get_connected() returns an array, you have to use the return value as an array, not a string.
So I tried this code snippet instead:
add_filter( 'render_block', function( $block_content, $block ) {
if ( !is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'licensee-name' ) !== false ) { // CSS class 'licensee-name' to be added to the block where the value should be output
$myreplace1 = 'placeholder'; // Block content should be set to the word 'placeholder'
$myinsert1 = implode(
MB_Relationships_API::get_connected( [
'id' => 'licensee-events',
'to' => get_the_ID(),
] ),
); // Relationship value to retrieve
$block_content = str_replace( $myreplace1, $myinsert1 , $block_content );
}
return $block_content;
}, 10, 2 );
It still doesn’t work, but at least it doesn’t break the loop entirely. However the block where I’m trying to display the data is empty. What am I doing wrong?
I’ve been researching this for weeks and could really use some help… thank you!
PS: I assume it’s obvious, but I’m no PHP expert. I’m mostly taking code snippets elsewhere and trying to tweak them to my needs.
Leave an answer