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?
Thanks for your suggestions! I completely forgot about this issue, but I just tested this for future reference and it turns out that $post
object isn’t available yet when registering ACF Blocks using acf/init
action (as suggested in the acf_register_block_type documentation). So it’s probably better to just put the data in data-attributes in the template/render_callback and read them from there, or pass them some other way, especially if it’s just a few parameters.
You must be logged in to reply to this topic.
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!
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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.