Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've searched a lot for this and I seem to get different answers.

In my situation, my jQuery function has to use a PHP variable from a different file.

How can I accomplish this? Clear and simple answer would be greatly appreciated.

share|improve this question
    
Is it your own file or a WordPress core file? And are you loading the script with wp_enqueue_script? –  ferenyl Sep 12 '13 at 8:01
    
None of the files I mentioned are core files. All are created by me. EDIT: Yes, I can run scripts in the JS file. –  user1526570 Sep 12 '13 at 8:02
    
This is off topic and should be moved to StackOverflow. –  anu Sep 12 '13 at 8:14
    
It depends. If it is about how to do it in WordPress it should stay. –  ferenyl Sep 12 '13 at 8:18

2 Answers 2

In general, this function lets you localize your JS strings, but you can also use it to set global JS variables:

function set_my_js_var() {
    // logic here for returning the right JS var
    $myVar = "Hello World";
    return $myVar;
}
function load_fe_scripts() {
    wp_enqueue_script( 'global-js-var', get_template_directory_uri() . '/js/my_file.js' );
    $localize_array = array(
        'my_js_var' => set_my_js_var()
    );
    wp_localize_script( 'global-js-var', 'my_global', $localize_array );
}
add_action('wp_enqueue_scripts', 'load_fe_scripts');

You can now acces the var in your JS File by my_global.my_js_var

share|improve this answer

You could use ajax to get the value from a function read about it here: http://codex.wordpress.org/AJAX_in_Plugins

you can also save the variable in the database with transients if the function runs on every load. http://codex.wordpress.org/Transients_API

then use http://codex.wordpress.org/Function_Reference/wp_localize_script to load the var to a global javascript var.

Update: This is a ugly way to do this. In your template where you want to save the var:

<script type="text/javascript">
 <?php print_var(); ?>
</script>

And in your function:

<?php
// register a global outside the function
global $myVar;
function MyFunc(){
global $myVar;
...
//save the var in the global!
$MyVar = $a;
...
}

//function
function print_var(){
global $MyVar;
 echo "var myGlobalJsVar = ". $MyVar .";";
}

?>
share|improve this answer
    
I was hoping for a simpler answer. I have variable $a = 1. All I want to do is pass $a to my script.js. –  user1526570 Sep 12 '13 at 8:22
    
When does the function run in the lifecycle? is it before or after wp_enqueue_script? if it is you can use wp_localize_script. Or you can use a ugly hack. i will update my answer with it. –  ferenyl Sep 13 '13 at 4:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.