Support

Account

Home Forums Gutenberg ACF Blocks – Pass field value to script

Helping

ACF Blocks – Pass field value to script

  • Is it possible to pass a post field value to script in acf_register_block_type() using wp_localize_script()? Tried with plain get_field('field_key'), tried getting them with $post->ID (example below) and get_queried_object_id(), but none of them seem to work.

    
    wp_localize_script( 'handle', 'object_name', array(
    	'jsVar' => get_field('field_key', $post->ID)
    ));
    

    I can pass fields in settings pages easily like:

    
    wp_localize_script( 'handle', 'object_name', array(
    	'jsVar' => get_field('field_key', 'page_id')
    ));
    

    but can’t get the post fields to work.

    I know I can work around this by putting the values in data-attributes in the block template and reading them from there, but I’m wondering if it’s possible to pass them with wp_localize_script. There’s no mention about this in the documentation.

  • This should definitely be possible and I don’t know why your first example shouldn’t work, but I guess that there are 2 possible causes:

    Possibility 1: Is it possible that when/where you call wp_localize_script the $post object is not (yet) available?

    You could check this by doing this:

    wp_localize_script( 'handle', 'object_name', array(
    	'jsVar' => $post->ID
    ));

    If the ‘jsVar’ is not set with the right postID, you have found your problem.

    In that case you could get it to work by doing this for example:

    global $post;
    wp_localize_script( 'handle', 'object_name', array(
    	'jsVar' => get_field('field_key', $post->ID)
    ));

    If that doesn’t work the post might not yet be available at the moment you call wp_localize_script. You should try changing what action you hook this function into. (Since you mention acf_register_block_type() I think you might be calling it directly from the template/render_callbak?)

    You could try this:

    add_action( 'wp_enqueue_scripts', function(){
      'jsVar' => get_field('field_key', $post->ID)
    });

    Possibility 2: Are you 100% sure that the post has a field with field_key?

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.