gutenberg icon indicating copy to clipboard operation
gutenberg copied to clipboard

'wp_head' hook in 'render_block' filter not working for classic theme (FSE theme works)

Open s56bouya opened this issue 4 years ago • 3 comments

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

  1. Add core paragraph block.
  2. 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

s56bouya avatar Sep 09 '22 10:09 s56bouya

Can someone please reproduce it?

s56bouya avatar Sep 12 '22 06:09 s56bouya

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.

t-hamano avatar Sep 19 '22 05:09 t-hamano

Thank you for your help. I will try using pre_render_block or render_block_data.

s56bouya avatar Sep 20 '22 02:09 s56bouya