admin管理员组文章数量:1333201
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.
本文标签: theme developmentHow to enqueue scripts and styles only when there are needed
版权声明:本文标题:theme development - How to enqueue scripts and styles only when there are needed? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742347056a2457734.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论