使用wp_localize_script无法正确传递数据

时间:2016-06-20 08:31:24

标签: javascript php wordpress

我试图将PHP数据传递给JS脚本。 我正在使用wp_localize_script函数。

wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js');
wp_register_script('mygaloochart_script', plugins_url('chart.js', __FILE__), array('googlechart'));

//I'm not using $atts directly for reasons
$dataToBePassed = array (
        'chart' => $atts['chart'],
        'element' => $atts['element'],
        'elementtype' => $atts['elementtype'],
        'title' => $atts['title']
);

wp_localize_script('mygaloochart_script', 'php_vars', $datatoBePassed);

wp_enqueue_script('googlechart');
wp_enqueue_script('mygaloochart_script');

这是JS脚本mygaloochart_script的第一行:

console.log(php_vars.chart);

但是,我在控制台中收到以下错误:

TypeError: php_vars is null

我做错了什么?

2 个答案:

答案 0 :(得分:0)

由于我的声誉,我无法发表评论。只是好奇地问,你是否挂了类似下面的函数?

<强>更新

function add_vars_to_js(){

wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js');
wp_register_script('mygaloochart_script', plugins_url('chart.js', __FILE__), array('googlechart'));

//I'm not using $atts directly for reasons
$dataToBePassed = array (
        'chart' => $atts['chart'],
        'element' => $atts['element'],
        'elementtype' => $atts['elementtype'],
        'title' => $atts['title']
);

wp_localize_script('mygaloochart_script', 'php_vars', $datatoBePassed);

wp_enqueue_script('googlechart');
wp_enqueue_script('mygaloochart_script');
}

add_action('wp_enqueue_scripts', 'add_vars_to_js');

答案 1 :(得分:0)

您的数组名称为$dataToBePassed。但是,您在$datatoBePassed函数中传递了wp_localize_script。大T,小T。 PHP 变量名称区分大小写