简体   繁体   中英

Including a javascript file whe when creating a wordpress plugin

I am developing a wordpress plugin and cannot get the javascript file to run. My javascript file looks like this:

<script>

    jQuery(document).ready(function($) {

        alert("Javascript is running");
    });

</script>

This is the code in the main plugin php file where I am trying to load the scripts:

function super_plugin_scripts() {

    wp_register_script('super_plugin_script', get_template_directory_uri().'js/super-plugin.js');
    wp_enqueue_script('super_plugin_script');
}

add_action('wp_enqueue_scripts', 'super_plugin_scripts');

I have also tried to run those two statements in the initialisation function but no luck.

您的javascript文件应包含原始js代码,没有标记[因此没有<script>标记,而只有其内容]。

Two things:

  1. make sure the path is right
  2. make sure jQuery is included in your WordPress, if not add this line wp_enqueue_script('jQuery');

like this

    function super_plugin_scripts() {
        wp_register_script('super_plugin_script', get_template_directory_uri().'js/super-    plugin.js');

        wp_enqueue_script('jQuery');
        wp_enqueue_script('super_plugin_script');
    }
    add_action('wp_enqueue_scripts', 'super_plugin_scripts');

It's a plugin and not a theme so try this out:

function super_plugin_scripts() {

    wp_register_script('super_plugin_script', plugin_dir_url(__FILE__).'js/super-plugin.js');
    wp_enqueue_script('super_plugin_script');
}

add_action('wp_enqueue_scripts', 'super_plugin_scripts');

plugin_dir_url requires you to pass in __FILE__ and it should figure out the path.

Managed to fix the problem. Used the plugins_url() function and then appended the name of the plugin to the front of the javascript file path like so:

wp_register_script('super_plugin_script', plugins_url().'/super-plugin/js/super-plugin.js');

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM