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!

1 Answer
1

I 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.

Leave a Reply

Your email address will not be published. Required fields are marked *