最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

theme development - How to enqueue scripts and styles only when there are needed?

programmeradmin2浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论