'wp_head' hook in 'render_block' filter not working for classic theme (FSE theme works)
Description
I want to add code inside the
if a certain block exists, using the 'render_block' filter.Works FSE theme (Twenty Twenty-Two). Not working classic theme (Twenty Twenty-One).
Please let me know if there is a mistake in the code or if there is another way to achieve it.
Step-by-step reproduction instructions
- Add core paragraph block.
- Use add_filter 'render_block_core/paragraph' and add_action 'wp_head'.
Screenshots, screen recording, code snippet
add_filter( 'render_block_core/paragraph', 'abc_render_block', 10, 2 );
function abc_render_block( $block_content, $block ) {
add_action( 'wp_head', function() {
?>
<style>
.wp_head_example {
background-color : #f1f1f1;
}
</style>
<?php
} );
return $block_content;
}
Environment info
- WordPress 6.0.2
Please confirm that you have searched existing issues in the repo.
Yes
Please confirm that you have tested with all plugins deactivated except Gutenberg.
Yes
Can someone please reproduce it?
I was able to reproduce this issue.
I think do_action( 'wp_head' ) may be already executed when rendering the block in the classic theme:
add_filter(
'render_block_core/paragraph',
function( $block_content ) {
// 0 is displayed in the block theme
// 1 is displayed in the classic theme
echo did_action( 'wp_head' );
// In the classic theme, it does not fire because it is after the do_action is executed
add_action( 'wp_head', function() {
?>
<style>p {background: #ccc;}</style>
<script>console.log( 'Should show when there is a paragraph block' );</script>
<?php
} );
return $block_content;
}
);
I think this isn't a bug because I believe that this is due to differences in rendering timing between the classic theme and the block theme.
In the classic theme, this could be handled by a more up-front hook such as pre_render_block or render_block_data instead.
Thank you for your help.
I will try using pre_render_block or render_block_data.