Get php var inside javascript file (making plugin)

You can use wp_localize_script() to pass php variables to javascript. You create an array in php and then pass it to the function as the third parameter. It will come through as an object you name with the second parameter.

First, register the script.

wp_register_script( 'custom-name-js', plugins_url( 'assets/custom-js.php', __FILE__ ) );

Second, build your array and run wp_localize.

$my_array = array( 'description' => $description[0]->option_value );
wp_localize_script( 'custom-name-js', 'js_object_name', $my_array );

Finally, you enqueue your script.

wp_enqueue_script( 'custom-name-js' );

Then, in your js file, you will have a js object available named js_object_name (or whatever you pass as the second parameter to wp_localize_script) with a property of description.

js_object_name.description

Leave a Comment