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?
1 Answer
Reset to default 0So, 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
版权声明:本文标题:plugin development - How can I obtain an option (get_option) inside a block viewScript? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736298839a1930312.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论