可以通过wp_localize_script
函数来实现,该函数是用于本地化的,也可用来输出JS对象。该函数可以将一个js对象输出到最终的html中,从而可以在JS中使用该对象。
该函数有三个参数:第一个参数为对应脚本的handler(即wp_enqueue_script
的第一个参数),第二个参数是生成的JS变量的变量名,第三个参数为变量值,可以是各种类型,会通过json_encode
输出到html中。
注意点:必须先用wp_enqueue_script
注册对应的脚本,之后才能使用该函数,不然无效
实例
wp_enqueue_script($this->plugin_name . '_widget', plugin_dir_url(__FILE__) . 'js/xxx.js', array('jquery'), $this->version, true);
$widget_options = array( 'margin_top' => $options['margin-top'], 'margin_bottom' => $options['margin-bottom'], 'xxx' => 'xxx', ); wp_localize_script($this->plugin_name . '_widget', 'widget_options', $widget_options);
JS中访问:例如widget_options.margin_top
文章评论