問題描述

有沒有可能在 JavaScript 中傳遞一些 PHP 變量,以便稍後使用它們?

只有在 single.php 。我聽説過 wp_enqueue_scripts,但是它是必須要聲明一個 JS 文件的路徑,但我不需要一個。

最佳解決方案

最佳做法

看看 wp_localize_script,這是為了做到這一點。

但是它需要先前使用 wp_enqueue_scripts,因此您需要將 JS 移動到單獨的文件。當然,這將是值得的幾分鐘的努力。

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' );

在 JS 中,您將可以使用傳遞的參數,如下所示:

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] );
}

[編輯] 你的情況

根據你的評論

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.

將以下主題的/js/文件夾,創建它,如果它不存在。我們來調用文件 fb-response.js

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

然後註冊,排隊和本地化,如上所示。假設你有你要傳遞的 ID,讓我們説 $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 ) );

注:顯然,上面假設這是一個主題。如果我們在説”plugin”,請相應地改變位置。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。