Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Equivalent to has_block for use in templates #38120

Closed
colinduwe opened this issue Jan 21, 2022 · 3 comments
Closed

Equivalent to has_block for use in templates #38120

colinduwe opened this issue Jan 21, 2022 · 3 comments
Labels
[Type] Question Questions about the design or development of the editor.

Comments

@colinduwe
Copy link
Contributor

What problem does this address?

In a block theme, I would like to be able to determine if the template includes a block. In post content the has_block() function does that. My use case is to enqueue some JS in the case the pagination block is in the template.

This is similar to #14758

What is your proposed solution?

Is there a function that would return the current template as string to pass to has_block()?

@karmatosed karmatosed added the [Type] Question Questions about the design or development of the editor. label Jan 21, 2022
@aristath
Copy link
Member

In a block theme, all blocks are parsed before the <head>. What that means, is ou can hook in render_block, and enqueue your script if the block exists.
Example:

add_filter( 'render_block', function( $block_content, $block ) {
	// Make sure we have the blockName.
	if ( empty( $block['blockName'] ) ) {
		return $block_content;
	}

	// If this is a pagination block, enqueue the pagination script.
	if (
		'core/query-pagination' === $block['blockName'] ||
		'core/query-pagination-next' === $block['blockName'] ||
		'core/query-pagination-previous' === $block['blockName'] ||
		'core/query-pagination-numbers' === $block['blockName']
	) {
		wp_enqueue_script( 'my-pagination-script' );
	}

	// Return the block content.
	return $block_content;
}, 10, 2 );
@colinduwe
Copy link
Contributor Author

Thank you!

@rku4er
Copy link

rku4er commented Sep 7, 2022

Is there a similar solution that works in site editor?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Type] Question Questions about the design or development of the editor.
4 participants