Pass PHP variable to javascript

Last Updated: September 22, 2021

How to pass PHP variable to javascript when you develop WordPress plugins

You can use the wp_localize_script function to do this

wp_enqueue_script('f_cal', plugins_url('codekayak-booking') . '/assets/js/front_cal.js', array(),1);
   
$script_params = array(
    'paypalSandboxClientId' => get_option(OPTION_PREFIX. 'paypalSandboxClientId' ),
);

wp_localize_script( 'f_cal', 'scriptParams', $script_params );

In the above example, you can see how the parameters are passing to front_cal.js javascript file.

You can access the parameters in your javascript file following way

alert(scriptParams.paypalSandboxClientId);