最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugins - Pass PHP variable to javascript

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Apr 18, 2013 at 22:23 Johannes P. 11.1k3 gold badges42 silver badges53 bronze badges asked Apr 18, 2013 at 22:02 Sebastian Corneliu VîrlanSebastian Corneliu Vîrlan 2931 gold badge2 silver badges9 bronze badges 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. – Sebastian Corneliu Vîrlan Commented Apr 18, 2013 at 22:23
Add a comment  | 

3 Answers 3

Reset to default 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.

https://developer.wordpress/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/.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/.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(),
    ];
}));

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')" />';
发布评论

评论列表(0)

  1. 暂无评论