简体   繁体   English

将JavaScript排入Wordpress插件

[英]Enqueue JavaScript into Wordpress plugin

-I am trying to include JavaScript file in my plug-in. - 我想在我的插件中包含JavaScript文件。 For testing I am calling a JavaScript function fun(). 为了测试我正在调用JavaScript函数fun()。

-My plug-in directory structure is: - 我的插件目录结构是:

(first-plugin, (js, 'animate.js'), 'first_plugin.php') (first-plugin,(js,'animate.js'),'first_plugin.php')

Above given directory format is like this (dirname, content_in_the_dir_separated_by_comma). 上面给出的目录格式是这样的(dirname,content_in_the_dir_separated_by_comma)。

-Here is my main plugin file code: - 这是我的主要插件文件代码:

function wl_include_files() {
    wp_enqueue_script('wl_js', plugin_dir_path( __FILE__ ) . '/js/animate.js', array( 'jquery' ));
}

function wl_activate_plugin() {
    add_action('admin_enqueue_scripts', 'wl_include_files');
}

//
register_activation_hook(__FILE__, 'wl_activate_plugin');

function test() {
    $v = "<script>fun();</script>";
    echo $v;
}

//
add_action('admin_init', 'test');

-Here is my JavaScript file code: - 这是我的JavaScript文件代码:

console.log('hi, file included properly.');

function fun() {
    alert("Hey, Someone calling me.");
}

-I am getting following error in my console: - 我的控制台出现以下错误:

ReferenceError: fun is not defined ReferenceError:未定义fun

-Can anybody tell what is the problem? - 任何人都可以说出问题是什么?

The admin_init() hook is triggered before any other hook when a user accesses the admin area. 当用户访问管理区域时,在任何其他挂钩之前触发admin_init()挂钩。 This means that test() is being called before any part of the page is constructed. 这意味着在构造页面的任何部分之前调用test() Or in other words, fun() would be called before even the <html> tag and more to the point, before animate.js is included in <head> . 或者换句话说,在<head>包含animate.js之前,甚至在<html>标签之前调用fun()并且更多地调用。

test.php (main plugin file inside test plugin directory) test.php(测试插件目录下的主插件文件)

//this wp_footer hook is called once the entire front-end page body has been constructed
add_action('wp_footer', 'test');

wp_enqueue_script( 'myjs', plugin_dir_url( __FILE__ ) . '/js.js');

function test()
{
    echo '<script>test();</script>';
}

js.js (inside same test directory) js.js(在同一测试目录中)

function test()
{
    console.log("Function called.");
}

(function ()
{
    console.log('JavaScript successfully included.');
})();

Further links: 更多链接:

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

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