Skip to content
Advertisement

how to load Javascript in WordPress Plugin

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.

<?php
/*
Plugin Name: Ava Test
Plugin URI: http://#.com
Description: A plugin that is used for my javascript tests
Author: Ronny Kibet
Author URI: http://ronnykibet.com
version: 1.001
*/

include(popup.js); 
/*when I include it this way, it works fine, but gives an error when I activate the plugin
'plugin generated 453 characters ...'
*/

function popup() {
$src = plugins_url('popup.js', __FILE__);
wp_register_script( 'popup', $src );
wp_enqueue_script( 'popup' );
}
/*
when I included it this way, plugin is activated but nothing happens.
*/
?>

this is the popup.js

<script type="text/javascript">

function popup(){


alert('hello there this is a test popup')

}
</script>
<body onload="popup()">
</body>

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.

<?php
/*
Plugin Name: Ava Test
Plugin URI: https://matsio.com
Description: A plugin that is used for my javascript tests
Author: Ronny Kibet
Author URI: https://matsio.com
version: 1.001
*/

add_action('wp_enqueue_scripts','ava_test_init');

function ava_test_init() {
    wp_enqueue_script( 'ava-test-js', plugins_url( '/js/ava_test_.js', __FILE__ ));
}

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement