I’m new with creating plugins for WP and I’m still learning. I have two questions concerning the same issue:
1:
First I included the js-file in my plugins 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' );
It works but what I want to do is to locate it from my plugins url (wordpress/wp-content/plugins/example), not from my template directory. How do I do this?
2:
In my js-file, I need to include some image files from the plugin base url (wordpress/wp-content/plugins/example/pix). This script worked when not used as a plugin:
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';
}
I understand that bp='/pix/',
is wrong. But what is correct? I want to load the images from a folder in template_directory
. How do I do this? I have read through these two threads but I cant seem to figure it out:
WordPress: How can I pick plugins directory in my javascript file?
You can use
plugins_url()
to enqueue scripts from the plugin directory.In your case, it would be something like:
To make the plugin url path available in javascript, you can use
wp_localize_script()
in combination with for exampleplugin_dir_url()
(which you also can use above I guess…).So the end result would be something like:
And in your javascript you will have the
wordpress_vars
variable available. Your plugin path will bewordpress_vars.plugin_path
.Note that I have modified the
wp_localize_script
to send an array as its 3rd argument.