4

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 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Definitely way better than use JS in your PHP files and use echo :-D
Amazing solution
1

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>

Comments

0

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

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

1 Comment

It's not working :/ All i get is alert with: <?php echo _URL; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.