Can someone show me how to include this javascript file into my wordpress plugin. I have tried all the wp_enqeue_script() methods but nothing happens.
ok here is my example plugin code with comments explaining what I would like.
JavaScript
x
25
25
1
<?php
2
/*
3
Plugin Name: Ava Test
4
Plugin URI: http://#.com
5
Description: A plugin that is used for my javascript tests
6
Author: Ronny Kibet
7
Author URI: http://ronnykibet.com
8
version: 1.001
9
*/
10
11
include(popup.js);
12
/*when I include it this way, it works fine, but gives an error when I activate the plugin
13
'plugin generated 453 characters ...'
14
*/
15
16
function popup() {
17
$src = plugins_url('popup.js', __FILE__);
18
wp_register_script( 'popup', $src );
19
wp_enqueue_script( 'popup' );
20
}
21
/*
22
when I included it this way, plugin is activated but nothing happens.
23
*/
24
?>
25
this is the popup.js
JavaScript
1
12
12
1
<script type="text/javascript">
2
3
function popup(){
4
5
6
alert('hello there this is a test popup')
7
8
}
9
</script>
10
<body onload="popup()">
11
</body>
12
So does anybody know how to call this script to work correctly in wordpress plugin?
Advertisement
Answer
You need to specify when the load should happen, try this.
JavaScript
1
16
16
1
<?php
2
/*
3
Plugin Name: Ava Test
4
Plugin URI: https://matsio.com
5
Description: A plugin that is used for my javascript tests
6
Author: Ronny Kibet
7
Author URI: https://matsio.com
8
version: 1.001
9
*/
10
11
add_action('wp_enqueue_scripts','ava_test_init');
12
13
function ava_test_init() {
14
wp_enqueue_script( 'ava-test-js', plugins_url( '/js/ava_test_.js', __FILE__ ));
15
}
16
Also, there are errors in your JS, but I have seen the correct version in some answers, hope this helps
Update : There is a hook called wp_enqueue_scripts, as mentioned by @brasofilo which should be used in lieu of init for loading scripts.