'tag.htm'; break; case 'flag': $pre .= $default_pre .= 'flag.htm'; break; case 'my': $pre .= $default_pre .= 'my.htm'; break; case 'my_password': $pre .= $default_pre .= 'my_password.htm'; break; case 'my_bind': $pre .= $default_pre .= 'my_bind.htm'; break; case 'my_avatar': $pre .= $default_pre .= 'my_avatar.htm'; break; case 'home_article': $pre .= $default_pre .= 'home_article.htm'; break; case 'home_comment': $pre .= $default_pre .= 'home_comment.htm'; break; case 'user': $pre .= $default_pre .= 'user.htm'; break; case 'user_login': $pre .= $default_pre .= 'user_login.htm'; break; case 'user_create': $pre .= $default_pre .= 'user_create.htm'; break; case 'user_resetpw': $pre .= $default_pre .= 'user_resetpw.htm'; break; case 'user_resetpw_complete': $pre .= $default_pre .= 'user_resetpw_complete.htm'; break; case 'user_comment': $pre .= $default_pre .= 'user_comment.htm'; break; case 'single_page': $pre .= $default_pre .= 'single_page.htm'; break; case 'search': $pre .= $default_pre .= 'search.htm'; break; case 'operate_sticky': $pre .= $default_pre .= 'operate_sticky.htm'; break; case 'operate_close': $pre .= $default_pre .= 'operate_close.htm'; break; case 'operate_delete': $pre .= $default_pre .= 'operate_delete.htm'; break; case 'operate_move': $pre .= $default_pre .= 'operate_move.htm'; break; case '404': $pre .= $default_pre .= '404.htm'; break; case 'read_404': $pre .= $default_pre .= 'read_404.htm'; break; case 'list_404': $pre .= $default_pre .= 'list_404.htm'; break; default: $pre .= $default_pre .= theme_mode_pre(); break; } if ($config['theme']) { $conffile = APP_PATH . 'view/template/' . $config['theme'] . '/conf.json'; $json = is_file($conffile) ? xn_json_decode(file_get_contents($conffile)) : array(); } !empty($json['installed']) and $path_file = APP_PATH . 'view/template/' . $config['theme'] . '/htm/' . ($id ? $id . '_' : '') . $pre; (empty($path_file) || !is_file($path_file)) and $path_file = APP_PATH . 'view/template/' . $config['theme'] . '/htm/' . $pre; if (!empty($config['theme_child']) && is_array($config['theme_child'])) { foreach ($config['theme_child'] as $theme) { if (empty($theme) || is_array($theme)) continue; $path_file = APP_PATH . 'view/template/' . $theme . '/htm/' . ($id ? $id . '_' : '') . $pre; !is_file($path_file) and $path_file = APP_PATH . 'view/template/' . $theme . '/htm/' . $pre; } } !is_file($path_file) and $path_file = APP_PATH . ($dir ? 'plugin/' . $dir . '/view/htm/' : 'view/htm/') . $default_pre; return $path_file; } function theme_mode_pre($type = 0) { global $config; $mode = $config['setting']['website_mode']; $pre = ''; if (1 == $mode) { $pre .= 2 == $type ? 'portal_category.htm' : 'portal.htm'; } elseif (2 == $mode) { $pre .= 2 == $type ? 'flat_category.htm' : 'flat.htm'; } else { $pre .= 2 == $type ? 'index_category.htm' : 'index.htm'; } return $pre; } ?>plugins - Pass PHP variable to javascript
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugins - Pass PHP variable to javascript

programmeradmin0浏览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. 暂无评论