Enqueue JavaScript into WordPress plugin

-I am trying to include JavaScript file in my plug-in. For testing I am calling a JavaScript function fun().

-My plug-in directory structure is:

Read More

(first-plugin, (js, ‘animate.js’), ‘first_plugin.php’)

Above given directory format is like this (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:

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

-Can anybody tell what is the problem?

Related posts

1 comment

  1. The admin_init() hook is triggered before any other hook when a user accesses the admin area. This means that test() is being called before any part of the page is constructed. 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>.

    test.php (main plugin file inside test plugin directory)

    //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)

    function test()
    {
        console.log("Function called.");
    }
    
    (function ()
    {
        console.log('JavaScript successfully included.');
    })();
    

    Further links:

Comments are closed.