将JavaScript排队到Wordpress插件中

Enqueue JavaScript into Wordpress plugin

本文关键字:插件 Wordpress JavaScript 排队      更新时间:2023-09-26

-我试图在我的插件中包含JavaScript文件。为了测试,我调用一个JavaScript函数fun()。

-我的插件目录结构是:

(first-plugin (js、"animate.js")、"first_plugin.php")

上面给出的目录格式是这样的(dirname, content_in_the_dir_separated_by_comma)。

-这是我的主要插件文件代码:

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');

-这是我的JavaScript文件代码:

console.log('hi, file included properly.');
function fun() {
    alert("Hey, Someone calling me.");
}

-I得到以下错误在我的控制台:

ReferenceError: fun is not defined

-有谁能告诉我是什么问题吗?

当用户访问管理区时,admin_init()钩子在任何其他钩子之前被触发。这意味着在构造页面的任何部分之前调用test()。或者换句话说,fun()甚至在<html>标签之前被调用,更确切地说,在animate.js包含在<head>之前被调用。

test.php (test插件目录中的主插件文件)

//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(在同一个测试目录)

function test()
{
    console.log("Function called.");
}
(function ()
{
    console.log('JavaScript successfully included.');
})();
进一步链接:

  • https://codex.wordpress.org/Function_Reference/wp_enqueue_script
  • https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init
  • https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer