How to pass parameters (data) from plugin PHP to React

WordPress has a function, wp_localize_script() that can do this. You create an array of values that you want to access in your JavaScript file and then inject it as an object.

You would modify your enqueue function like this:

function include_react_files() {
  wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );

  // add the JS file to the footer - true as the last parameter
  wp_register_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(),  '0.0.1', true );
  $data = array( 
     'key1' => 'value1',
     'key2' =? 'value2',
  );
  wp_localize_script( 'plugin-scripts', 'object', $data );
  wp_enqueue_script( 'plugin-scripts' );
}

add_action( 'wp_enqueue_scripts', 'include_react_files' );

Then to access this data, you would simply do object.key1, object.key2, etc. So console.log( object.key1 ); will echo value1.

Leave a Comment