簡體   English   中英

將變量從WordPress PHP傳遞到JavaScript

[英]Passing Variable from WordPress PHP to JavaScript

我正在使用兩個WordPress插件-用於插入PHP代碼的片段和用於插入JavaScript的Scripts n Styles。

我的目標是獲取已登錄用戶的電子郵件地址並預先填寫表格。

片段中的PHP代碼是:

<?php
function get_user() {
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
}
add_action( 'init', 'get_user', 10 );
?>

腳本n樣式中的代碼為:

<script type="text/javascript">
window.onload = function () {

var useremail = "<?php echo json_encode($user_email); ?>";

document.getElementsByName("ElementName")[0].value = useremail;
}
</script>

但是,我沒有獲得user@domain.com,而是將引號插入了表單中:

<?php echo json_encode($user_email); ?>

有什么想法出了什么問題或獲得相同結果的更好方法的任何想法?

WordPress具有有用的功能,可以本地化要從PHP傳遞來在JavaScript中使用的腳本。 這可以通過在入隊腳本之前使用wp_localize_script()函數來完成。

這是WordPress Codex正在使用的示例。 https://codex.wordpress.org/Function_Reference/wp_localize_script

注冊並排隊腳本:

// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );

// Localize the script with new data
$translation_array = array(
    'some_string' => __( 'Some string to translate', 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );

在JavaScript中使用該數據:

// alerts 'Some string to translate'
alert( object_name.some_string);

以下是有關其工作原理的出色文章: http : //www.webtipblog.com/localize-scripts-in-wordpress-to-use-php-variables-in-javascript/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM