将变量从WordPress PHP传递给JavaScript

时间:2018-01-29 17:24:20

标签: javascript php jquery wordpress

我正在使用两个WordPress插件 - 用于插入PHP代码的片段和用于插入JavaScript的Scripts n样式。

我的目标是记录用户的电子邮件地址并预先填写表单。

Snippets中的PHP代码是:

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

Scripts n Styles中的代码是:

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

知道出了什么问题或者更好的方法来获得相同的结果吗?

1 个答案:

答案 0 :(得分:2)

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/