Home Forums Gutenberg ACF Blocks – Pass field value to script Reply To: ACF Blocks – Pass field value to script

  • 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?