0

If I traditionally enqueue a script...

wp_enqueue_script('some-script', $dependencies_script_path, array( 'wp-i18n' ), false, $load_in_footer);

I can use wp_add_inline_script to send info from wp_option table to the front end javascript this way:

$beautiful_option = get_option('beautiful');
wp_add_inline_script('some-script', 'const BEAUTIFUL_OPTION=' .$beautiful_option, 'before');

And then, in the javascript file, I can, magically access the constant:

doMagicalThingsWith(BEAUTIFUL_OPTION);

How can I do this on the viewScript of a block?

1 Answer 1

0

So, if I want to add any custom styles or scripts in a block's CSS or JS file, I usually add them in the PHP file associated with the block (the render property in block.json).

Add the following code to the PHP file at the end -

$beautiful_option = get_option('beautiful');
wp_add_inline_script('some-script', 'const BEAUTIFUL_OPTION=' .$beautiful_option, 'before');

Just make sure to add any appropriate checks and validations for the code. Seems a bit hacky but has worked so far for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.