简体   繁体   English

创建wordpress插件时包括一个javascript文件

[英]Including a javascript file whe when creating a wordpress plugin

I am developing a wordpress plugin and cannot get the javascript file to run. 我正在开发wordpress插件,无法运行javascript文件。 My javascript file looks like this: 我的JavaScript文件如下所示:

<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: 这是我尝试加载脚本的主要插件php文件中的代码:

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'); 确保jQuery包含在您的WordPress中,如果没有添加此行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. plugin_dir_url要求您传入__FILE__ ,它应该找出路径。

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: 使用plugins_url()函数,然后将插件名称附加到javascript文件路径的前面,如下所示:

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

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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