Search and replace some tags in a block to dynamically insert the title and excerpt.
I am working on a new site that will be similar to a existing client site that uses Elementor. I am trying to use Gutenburg (and some block plugins and maybe some custom ACF blocks) and not use Elementor.
I recently had to update some CTA links in the hero area on the Elementor based site. I had to edit every page on the site. It was tedious. For the new site I have been experimenting with Reusable Blocks. The immediate issue was that the block would need to have the page title. I could add the block to the page and break the reusable block connection but that would defeat the purpose of using a reusable block.
I decided to look at filtering the block content while it is being rendered and found the ‘render_block‘ filter. This is similar to ‘the_content‘ filter that is often used to append markup to.
Infinite Loop
The ‘render_block‘ filter function receives the block content and the block object. I reviewed the block object with a view to writing a generic search/replace solution but soon found that it was over engineering and that keeping it simple was better.
I wished to insert the page/post title and the excerpt. I quickly found that using get_the_excerpt() caused an infinite loop. This really wasn’t surprising as blocks would have to be rendered to get the excerpt text and would recursively call the ‘render_block‘ filter. Oops. The solution is to retrieve the excerpt directly from the post object.
I used the arrays of search and replace terms in the str_replace() call so it could be easily expanded to build up a big list of search/replace terms.
Leave a Reply