I have page created based on ACF and flexible fields layout. In my theme I have some JS scripts like masonry, fancybox, lazyload. For now im using standard wp_enqueue_style
in function.php
file. Is there any clever way to enqueue scripts only if certain block from ACF is chosen, and only once if this block was inserted earlier?
Thanks!
I have page created based on ACF and flexible fields layout. In my theme I have some JS scripts like masonry, fancybox, lazyload. For now im using standard wp_enqueue_style
in function.php
file. Is there any clever way to enqueue scripts only if certain block from ACF is chosen, and only once if this block was inserted earlier?
Thanks!
Share Improve this question edited Jun 15, 2020 at 18:28 D_P asked Jun 15, 2020 at 17:17 D_PD_P 1531 gold badge3 silver badges12 bronze badges1 Answer
Reset to default 1I use the following to enqueue a specific script on post.php
, which is triggered by the admin_enqueue_scripts
hook:
if ( in_array( get_current_screen()->base, [ 'post' ] ) ) {
// Load scripts only on the post edit page.
wp_enqueue_script( PLUGIN_NAME, PLUGIN_ROOT_URL . 'resources/js/script.js', [], PLUGIN_VERSION, false );
}
Instead of the check I do, you could retrieve the post's content and scan it for the block you require. Like so:
if ( is_singular() ) {
$post = get_post();
if ( $post && has_blocks( $post ) ) {
$blocks = parse_blocks( $post->post_content );
$postContainsBlock = ... // Search $blocks array for the required block.
if ( $postContainsBlock ) {
wp_enqueue_script( PLUGIN_NAME, PLUGIN_ROOT_URL . 'resources/js/script.js', [], PLUGIN_VERSION, false );
}
}
}
Note: I haven't tested the code above.