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

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:

Read More
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?

write php inside javascript alert

Related posts

1 comment

  1. You can use plugins_url() to enqueue scripts from the plugin directory.

    In your case, it would be something like:

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

    To make the plugin url path available in javascript, you can use wp_localize_script() in combination with for example plugin_dir_url() (which you also can use above I guess…).

    So the end result would be something like:

    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__)));
    }
    

    And in your javascript you will have the wordpress_vars variable available. Your plugin path will be wordpress_vars.plugin_path.

    Note that I have modified the wp_localize_script to send an array as its 3rd argument.

Comments are closed.