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

print_block css / js enqueuing #79

Open
rossberenson opened this issue Dec 22, 2022 · 0 comments
Open

print_block css / js enqueuing #79

rossberenson opened this issue Dec 22, 2022 · 0 comments

Comments

@rossberenson
Copy link

Hi,

Love the print_block function. Great for scaffolding or hardcoding some blocks in templates. What would the best practice be for enqueuing the block's css/js? When using a block normally, as you know, the css/js is enqueued. I was thinking of adding the css/js to the global css/scripts but that doesn't seem like the best solution. We would ideally want it to load only if the block is utilized.

I did modify the print_block function to enqueue but unsure if it's the best way to do it. It does the job but isn't my favorite. If this block is used in gutenberg, then the css / js is called twice. I was trying to think of a way to prevent that but I'm not sure of the block handles to prevent multiple enqueues of the same css/js.

function print_block( $block_name = '', $args = [] ) {
	if ( ! $block_name ) {
		return;
	}

	// extract args.
	if ( ! empty( $args ) ) {
		extract( $args ); //phpcs:ignore WordPress.PHP.DontExtract.extract_extract -- We can use it here since we know what to expect on the arguments.
	}

	wp_enqueue_style(
	    "$block_name-style",
	    get_theme_file_uri( "build/blocks/$block_name/style-script.css" ),
	    array(),
	    1.0
	);

	wp_enqueue_script(
	    "$block_name-script",
	    get_theme_file_path( "build/blocks/$block_name/script.js" ),
	    array(),
	    1.0
	);

	require get_template_directory() . '/src/blocks/' . $block_name . '/' . $block_name . '.php';
}

Any thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant