17

Is there any possibility to pass some PHP variables in javascript so I can use them later?

Only in single.php.
I heard about wp_enqueue_scripts but with that it is neccesary to declare a path to a JS file, but I don`t need one.

2
  • What do you meand by later, and where do you want to use the variables (with respect to where the PHP variables are)? You can of course echo/print JavaScript code via PHP, and thus insert PHP variable values. But this is not what you want, I guess...
    – tfrommen
    Commented Apr 18, 2013 at 22:17
  • I created a new db table with some response.id`s from facebook api. This is the table: action_id, user_id,post_id, fb_id where fb_id is response.id from a facebook action. Then in single.php I have a button where if I press I must delete the fb action with api: FB.api('/'+fb.response, 'delete'); where fb.response should be fb_id from table. Commented Apr 18, 2013 at 22:23

3 Answers 3

30

Best practice method

Have a look at wp_localize_script, which is meant to do exactly that.

But it does require previous usage of wp_enqueue_scripts, hence you will need to move your JS to a separate file indeed.
It will be worth those few minutes of effort though, for sure.

function wpse_96370_scripts()
{
    if ( is_single() ) {

        wp_register_script(
           'your_script_handle',
           get_template_directory_uri() . '/js/your-script.js',
           array( /* dependencies*/ ),
           1.0,
           true
       );

       wp_enqueue_script( 'your-script-handle' );

       $script_params = array(
           /* examples */
           'post' => 99,
           'users' => array( 1, 20, 2049 )
       );

       wp_localize_script( 'your-script-handle', 'scriptParams', $script_params );

    }
}
add_action( 'wp_enqueue_scripts', 'wpse_96370_scripts' );

In the JS you will then be able to use the passed parameters like so:

var posts = scriptParams.post,
    secondUser = scriptParams.users[1]; /* index starts at 0 */

// iterate over users
for ( var i = 0; i < scriptParams.users.length; i++ ) {
    alert( scriptParams.users[i] );
}

[Edit] Your situation

As per your comment

I created a new db table with some response.ids from facebook api. This is the table: action_id, user_id,post_id, fb_id where fb_id is response.id from a facebook action. Then in single.php I have a button where if I press I must delete the fb action with api: FB.api('/'+fb.response, 'delete'); where fb.response should be fb_id from table.

Put the following your theme's /js/ folder, create it, if it doesn't exist.
Let's call the file fb-response.js:

jQuery( '#button_id' ).click( function() {
    FB.api( '/' + fbParams.id, 'delete' );
});

Then register, enqueue and localize as seen above. Assuming that you have the ID you'd like to pass in let's say $fb_id:

wp_register_script(
    'fb-response',
     get_template_directory_uri() . '/js/fb-response.js',
     array( 'jquery' ),
     1.0,
     true
);

wp_enqueue_script( 'fb-response' );

wp_localize_script( 'fb-response', 'fbParams', array( 'id' => $fb_id ) );

N.B. Obviously, the above is assuming this is in a theme. If we're talking "plugin", alter locations accordingly.

14
  • I am a little begginer in this, so I try to implement this to my wordpress: papermashup.com/jquery-iphone-style-ajax-switch. As you can see there is a js file and a few lines of js code to put in the usage file. Or I can put that few lines of code on another file? Commented Apr 18, 2013 at 22:30
  • So for any small javascript action I should create a file? If you are avaible can you add on skype: sebyku17 ? Commented Apr 18, 2013 at 22:40
  • That depends on what you want to do, where you want to do that, and so on. Generally: No, you don't have to use an external JS file. But if you choose to, you can put whatever you want inside one single file. There's no need for multiple files if you have multiple functions, if that's what you were asking. However, you already accepted this (IMHO quite complex and in your case slightly overkill sort of) answer - without having fully understood, as I take it. No offense, @Johannes. ;)
    – tfrommen
    Commented Apr 18, 2013 at 22:45
  • 1
    None taken, @tf. So far it might be borderline overkill, but for one his code might grow and for another, the initial question spoke of "variables", in plural form. Your answer is just as valid though, so +1 from me. Commented Apr 18, 2013 at 22:49
  • 2
    wp_localize_script is a very underused and powerful function for passing PHP values to a Javascript file. It's surprising not many people actually know about this powerful feature in Wordpress. Commented Apr 19, 2013 at 0:32
2

https://developer.wordpress.org/reference/functions/wp_add_inline_script/ should be a preferred option nowadays

EDIT: From the docs above:

function mytheme_enqueue_typekit() {
   wp_enqueue_script( 'mytheme-typekit', 'https://use.typekit.net/.js', array(), '1.0' );
   wp_add_inline_script( 'mytheme-typekit', 'try{Typekit.load({ async: true });}catch(e){}' );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_typekit' );

So that you first enqueue the script, and then pass the variables

Yet this code simply generates the following

<script type="text/javascript" src="https://use.typekit.net/.js?ver=1.0"></script>
<script type="text/javascript"> try{Typekit.load({ async: true });}catch(e){} </script>

In my case, I simply expose the data I need directly writing the JavaScript code (in the template) and using a global JS variable with a specific name (haven't found a better way) (using Timber, pure PHP should be equivalent)

<script>
    my_global_variable.data1 = {{ custom_timber_function()|json_encode }}
</script>
$twig->addFunction(new Timber\Twig_Function('custom_timber_function', function () {
    return [
      'theme' => get_stylesheet_directory_uri(),
    ];
}));
2
  • 1
    I agree with your assessment, but answers should be self-sufficient and not only a link. Can you please add an example and an explanation? Commented Jul 20, 2020 at 16:12
  • completely right
    – GWorking
    Commented Jul 20, 2020 at 16:57
1

Having read your comment, I understand you'd like to do something like this:

// Do something to get the ID
$facebook_id = ...

// Create and print the button
echo '<input onclick="FB.api('/'+'.$facebook_id.', 'delete')" />';
3
  • No, this is the page where I am working: funny-videoro.com/the-dark-knight-rises-trailer-oficial . If you want you can login to the website. Then you will see a jquery ios style button. When I slide to off I must delete with fb api a post. The post id is in the db. Commented Apr 18, 2013 at 22:35
  • Well, that is basically what I wrote in my answer. Retrieve the id from the database and store it in a variable. Then directly print it into your one-line JavaScript function call. The <input ... /> and its function was for demonstrating purposes only. As far as I understood you, there's everything said what you need. If not, please try to explain some more, but in your question, not in comments.
    – tfrommen
    Commented Apr 18, 2013 at 22:39
  • I dont want to use php and js code in same line, in wordpress are some automatically functions ... Commented Apr 18, 2013 at 23:24

Your Answer

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

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