Wow, this is awesome! Exactly what I was looking for. Cheers, Carl!
No prob, but I just tried something that you may be able to advise on.
When I register the block in functions.php, I can use that wp_add_inline_script to execute code in the back end. But ACF doesn’t work in functions.php. Probably because it doesn’t know which block (or at least post) to pull this “slides_per_view” value from.
I think you need to target the post ID if you use ACF in functions.php, no? Which is why the last section of this doesn’t work as it does in my slider.php file.
acf_register_block_type(array(
'name' => 'slider',
'title' => __('Slider'),
'description' => __('A custom slider block.'),
'render_template' => 'inc/blocks/slider/slider.php',
'category' => 'formatting',
'icon' => 'images-alt2',
'align' => 'full',
'enqueue_assets' => function () {
wp_enqueue_script('swiper', 'https://unpkg.com/[email protected]/swiper-bundle.min.js', array(), '1.8.1', true);
$script = ‘var swiper = new Swiper(“.swiper”,
{slidesPerView:’.get_field(”slides_per_view”.’});’;
wp_add_inline_script(‘swiper’, $script);
}
No worries if you’re not sure. You’ve helped plenty.
Doh – dumb mistake on my part. Awesome, this works. Thanks.
One last thing. This doesn’t insert the script into the editor. Any way I can have it insert on the admin side as well? I’d love to have it work with the new full site editor.
Hi @hube2 , thanks for the help.
Your first comment unfortunately didn’t work – same results as before. For the wp_add_inline_script option, how do I add my php into that script?
The following code causes issues because I’m trying to put PHP in a JavaScript string (the $data parameter of wp_add_inline_script), I think:
<?php
wp_add_inline_script('swiper', '
var swiper = new Swiper(".swiper", {
slidesPerView: <?php the_field("slides_per_view"); ?>
});
')
?>
Any ideas?
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
The most recent ACF Chat Friday featured a live demo of how to register CPTs directly in the plugin, one of our most requested features. Check out the summary below for a replay of the demo, and don’t forget to register for the next session! https://t.co/k2KQ3WWBAz
— Advanced Custom Fields (@wp_acf) March 9, 2023
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.