-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:
(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?
The
admin_init()
hook is triggered before any other hook when a user accesses the admin area. This means thattest()
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, beforeanimate.js
is included in<head>
.test.php (main plugin file inside test plugin directory)
js.js (inside same test directory)
Further links: