Skip to content

Instantly share code, notes, and snippets.

@RyanNutt
Created December 2, 2019 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanNutt/9b2139e4da99f9dfb5570eb052c91f5a to your computer and use it in GitHub Desktop.
Save RyanNutt/9b2139e4da99f9dfb5570eb052c91f5a to your computer and use it in GitHub Desktop.

WordPress: Enqueue Script if has blocks

Not sure this is the best way to handle this, but it does work.

The other day I was working on a block plugin and needed a way to include JavaScript and CSS, but only if that block was in use. Relatively easy on single pages, but I wanted it to work on archive pages as well.

Turns out it doesn't take too much code to get a list of all the current post IDs and loop through each calling has_block along the way. Even better, this works for archive and single pages. If it's a singular page then $post_ids will be a 1 element array with that post. If it's an archive page the all the post IDs will be in that array.

<?php
add_action('wp_enqueue_scripts', 'enqueue_if_has_block');
function enqueue_if_has_block() {
$block_name = 'some/block';
global $wp_query;
$post_ids = wp_list_pluck( $wp_query->posts, 'ID' );
$has_block = false;
foreach ($post_ids as $id) {
if (has_block($block_name, $id)) {
$has_block = true;
break;
}
}
if ($has_block) {
// Enqueue whatever scripts and styles you want
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment