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?

  • 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())? Feb 20 '18 at 19:51
  • I haven't, and this seems to be exactly what I need. Thanks!
    – jshwlkr
    Feb 27 '18 at 20:48

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.org/reference/functions/wp_add_inline_script/)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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