admin管理员组

文章数量:1417463

I'm trying to build a gutenberg block (via plugin) that interfaces with a third-party api via credentials. I'm unsure how to, or even if I can, access a plugin's settings in gutenberg in order to grab a potential credentials field for use in the block. (I understand there's potential to put something in the editor's sidebar, but I need a persistent global setting that doesn't have to be set with every block.) Am I missing something in the documentation or is this not possible yet?

I'm trying to build a gutenberg block (via plugin) that interfaces with a third-party api via credentials. I'm unsure how to, or even if I can, access a plugin's settings in gutenberg in order to grab a potential credentials field for use in the block. (I understand there's potential to put something in the editor's sidebar, but I need a persistent global setting that doesn't have to be set with every block.) Am I missing something in the documentation or is this not possible yet?

Share Improve this question asked Feb 16, 2018 at 19:12 jshwlkrjshwlkr 5441 gold badge6 silver badges24 bronze badges 2
  • 2 Have you tried using wp_localize_script to make the variables from, say, a settings page available to your block registration script (using get_option())? – brianjohnhanna Commented Feb 20, 2018 at 19:51
  • I haven't, and this seems to be exactly what I need. Thanks! – jshwlkr Commented Feb 27, 2018 at 20:48
Add a comment  | 

2 Answers 2

Reset to default 7

The WordPress way to access PHP variables with JavaScript is to use wp_localize_script().

function wpse_enqueue_scripts(){
  wp_enqueue_script( 'wpse', PATH_TO . 'script.js' );
  wp_localize_script( 'wpse', 'credentials', $credentials );
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' );

Then in your JavaScript, you can access the credentials like

console.log( credentials );

Now, I believe wp_add_inline_script is maybe the better option. (https://developer.wordpress/reference/functions/wp_add_inline_script/)

本文标签: Accessing plugin settings in gutenberg