Sending data from template to script in gutenberg acf block

808 views Asked by At

I am registering custom block with ACF (acf_register_block_type) with a separate JavaScript file. In the php template I have some ACF data. Is it possible to send those data to the JavaScript? There are multiple instance of the same block in one page and the ACF data is unique to each instance. I am not sure how that works, because the JavaScript for block only loads once. I need some basic idea for this. The ACF data in the template file are quite a lot, so I could not just use data-attribute.

acf_register_block_type(array(
    'name'              => 'testimonial',
    'title'             => __('Testimonial'),
    'description'       => __('A custom testimonial block.'),
    'render_template'   => get_template_directory() . '/template-parts/blocks/testimonial/testimonial.php',
    'enqueue_script'    => get_template_directory_uri() . '/template-parts/blocks/testimonial/testimonial.js',
));

I am using this above example. SO in this case, I am trying to send data from testimonial.php to testimonial.js

1

There are 1 answers

0
S.Walsh On

In WordPress, the PHP function localize_script() is used to pass data from PHP to JavaScript, which could work for your scenario, eg:

<?php
function testimonial_enqueue_scripts()
{
    wp_enqueue_script('testimonial-script', get_template_directory_uri() . '/template-parts/blocks/testimonial/testimonial.js');
    wp_localize_script('testimonial-script', 'acf_vars', array(
        'data' => 'value to send to javascript'
    ));
}
add_action('wp_enqueue_scripts', 'testimonial_enqueue_scripts');
?>

In your JavaScript, the data can then be accessed as acf_vars.data