Pass PHP variable to javascript

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.


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() ) {

           get_template_directory_uri() . '/js/your-script.js',
           array( /* dependencies*/ ),

       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 =,
    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 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( "" +, '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:

     get_template_directory_uri() . '/js/fb-response.js',
     array( 'jquery' ),

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.

Leave a Comment