WordPress - Plugin -在js文件中从WP插件目录中排队图像文件


WordPress - Plugin - enqueue image files from WP plugin directory in a JS-file

我是新的创建插件的WP,我还在学习。对于同一个问题,我有两个问题:

1:首先,我在我的插件中包含了js文件php-file:

function theme_name_scripts() {
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js');
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

它的作品,但我想做的是找到它从我的插件url (wordpress/wp-content/plugins/example),而不是从我的模板目录。我该怎么做呢?

2:在我的js-file中,我需要包括一些来自插件基础url的图像文件(wordpress/wp-content/plugins/example/pix)。这个脚本在不作为插件使用时也可以工作:

window.onload=function()
{
/* Example */
bp='/pix/', // base url of my images
imgnum=4, // number of images
thumb1=document.getElementById('thumb1'), // id of changing image
combobox1=document.getElementById('selection1'); // id of combobox.
combobox1.onchange=function()
{
thumb1.src=bp+'imagefile'+this.value+'.png';
}

我理解bp='/pix/',是错误的。但是什么是正确的呢?我想从template_directory中的文件夹加载图像。我该怎么做呢?我已经通读了这两个线程,但我似乎不能弄清楚:

我如何在我的javascript文件中选择插件目录?

您可以使用plugins_url()从插件目录中加入脚本。

在你的例子中,它应该是这样的:

function theme_name_scripts() {
  wp_register_script('script-name', plugins_url('js/example.js', __FILE__));
}

要使插件url路径在javascript中可用,您可以使用wp_localize_script()结合例如plugin_dir_url()(你也可以使用上面我猜…)。

那么最终的结果会是这样的:

function theme_name_scripts() {
  // register your script
  wp_register_script('script-name', plugins_url('js/example.js', __FILE__));
  // or
  // wp_register_script('script-name', plugin_dir_url(__FILE__) . 'js/example.js');
  // make variables available in javascript
  wp_localize_script('script-name', 'wordpress_vars', 
                     array('plugin_path' => plugin_dir_url(__FILE__)));
}

在你的javascript中,你将有wordpress_vars变量可用。您的插件路径将是wordpress_vars.plugin_path

注意,我已经修改了wp_localize_script发送一个数组作为它的第三个参数。