admin管理员组

文章数量:1122846

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?

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?

Share Improve this question asked Aug 3, 2024 at 3:52 IoguiIogui 1416 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

本文标签: plugin developmentHow can I obtain an option (getoption) inside a block viewScript