How to read global variable from WP-Config.php in JS file

Viewed 1934

I have defined URL in wp-config file.

DEFINE('URL', 'google.com');

Now i want to access this URL from my JS theme file:

<script> alert(URL); </script>

How to do this?

3 Answers

use localize in functions.php

add_action('wp_enqueue_scripts' , function(){ 
  wp_localize_script('jquery', 'config_var', URL );
});

and in js file => config_var will equal the config variable value

You have to put a bit of your JS in your PHP file (i.e. use script tags to accomplish this). Then do the following:

  1. Place the script in your php file
  2. <script> alert(<?php echo URL ?>); </script>

you can read the php variable inside th js using echo. use like this

var url='<?php echo _URL; ?>';
 alert(url);
Related