我意识到这是一篇较旧的帖子,但老实说,我不知道以下是否是将参数从插件传递到 javascript 的可接受方式,但我遇到了同样的问题,并且想分享至少一种方法!也很高兴收到反馈!
出于某种原因,我最终使用了两种不同的方式将参数从插件 PHP 代码传递到 JS 代码。
第一个使用 wp_localize_script 选项相当简单。
这里是插件 PHP sn-p:
wp_enqueue_script(
'dynamic-rss-scripts', /* Handle/Name */
plugin_dir_url( __FILE__ ) . 'assets/js/dynamic-rss.js', /* Path to the plugin/assets folder */
//array('jquery', 'xml2json', 'json2xml'), /* Script Dependencies */
array('jquery'), /* Script Dependencies */
null, /* null is any version, but could be the specific version of jquery if required */
false /* if true=add to footer, false=add to header */
);
/*
Pass any server-side vars down to JS. These will be exposed as
php_vars.variablename for example
*/
$jsarray = array(
'exampleparam' => 'Example Param Value'
);
wp_localize_script( 'dynamic-rss-scripts', 'php_vars', $jsarray );
我使用的是数组,因为在我的情况下,我通常需要传递一些参数。
从上面的 sn-p 中,实际的参数值在 Javascript 中很容易使用。 请注意上述 PHP 中 wp_localize_script 行中的 php_vars 引用。
因此,在 Javascript 中,通过这样做很容易引用这些参数:
console.log('Hello to PHP variables', php_vars);
...在我使用上述 PHP sn-p 的情况下,我现在当然可以通过以下方式引用我的 exampleparam 参数:
console.log('Here is my specific param called exampleparam', php_vars.exampleparam);
我使用的第二种方法是简单地在 DOM 元素上构造数据属性(在我的例子中,这是一个容器 DIV)。
在我的插件 PHP 中,我提取了插件/简码参数:
extract(shortcode_atts(数组(
'url' => '',
'feed-type' => 'list', // This could be for Wordpress or Calendar etc.
'rows' => '5',
'cols' => '1',
'include-image' => 'false',
'image-align' => 'left',
'image-size' => '100',
'include-date' => 'true',
'date-format' => 'dd/mm/yyyy'
), $attrs ));
我做了一些验证等,但最终我只是创建了这样的 HTML 数据属性:
$content = "<div id='dynamic-rss' class='dynamic-rss-container' ";
$content .= "data-url='" . $attrs['url'] . "' ";
$content .= "data-feedtype='" . $attrs['feed-type'] . "' ";
$content .= "data-rows='" . $attrs['rows'] . "' ";
$content .= "data-cols='" . $attrs['cols'] . "' ";
$content .= "data-includeimage='" . $attrs['include-image'] . "' ";
$content .= "data-imagealign='" . $attrs['image-align'] . "' ";
$content .= "data-imagesize='" . $attrs['image-size'] . "' ";
$content .= "data-includedate='" . $attrs['include-date'] . "' ";
$content .= "data-dateformat='" . $attrs['date-format'] . "'";
$content .= "></div>";
然后我在 PHP 中返回 $content,它使用数据属性呈现该容器 DIV。
在 Javascript/jQuery 中的最后一步(我在这里使用 jQuery,但可以是直接的 JS)是检索数据属性,然后您可以在 Javascript 代码中的任何需要的地方使用:
const feedUrl = $('#dynamic-rss').data('url');
const feedType = $('#dynamic-rss').data('feedtype');
const rows = returnInt($('#dynamic-rss').data('rows')) != NaN ? returnInt($('#dynamic-rss').data('rows')) : 10;
const cols = returnInt($('#dynamic-rss').data('cols')) != NaN ? returnInt($('#dynamic-rss').data('cols')) : 1;
const includeImage = $('#dynamic-rss').data('includeimage');
const imageAlign = $('#dynamic-rss').data('imagealign');
const imageSize = $('#dynamic-rss').data('imagesize');
const includeDate = $('#dynamic-rss').data('includedate');
const dateFormat = $('#dynamic-rss').data('dateformat');
如果其他人偶然发现这件事,希望这会有所帮助!