Add javascript to wordpress through plugin

You can add the any javascript through theme. But some times many clients wants simple wordpess plugin which will inject javascript code into wordpress site.  Here we have simple wordpress plugin code which Add javascript to wordpress through plugin and inject the javascript tag into head section of wordpress site.

Add javascript to wordpress through plugin

Here I will give very simple wordpress plugin code which inject the javascript tag into head section of wordpress site. You need to use my following code for creating the wp plugin. Create file with”wpapi_js.php” name and put following code in to that file.

Put this file under wp-content/plugins folder. Go to admin bashboard, plugin section. You will able to see the wpapi_js Ads plugin over there. After activating the plugin you will find. Javascript file will be added into head section.

<?php

/*

Plugin Name: wpapi_js Ads

Plugin URI: http://www.wpapi.com/

Description: wpapi_js Ads Plugin will add the ad slot to wordpress site

License: GNU General Public License 2.0 (GPL) http://www.gnu.org/licenses/gpl.html

Version: 1.0

Author: Purab Kharat

Author URI: http://www.wordpresapi.com/

*/

if ( !defined('wpapi_js_AD') ) {

define('wpapi_js_AD',get_option('siteurl').'/wp-content/plugins/'.plugin_basename(dirname(__FILE__)).'/');

} else {

define('wpapi_js_AD',WP_CONTENT_URL.'/plugins/'.plugin_basename(dirname(__FILE__)).'/');

}

function wpapi_js_init() {
 if (!is_admin()) {
 wp_enqueue_script('the_js', 'http://yourjspath.com/test.js' );
 }
}
add_action('init', 'wpapi_js_init');

?>

If you want to add the javascript script for only wordpress admin panel then use following code.

 

//Load script to admin panel
function admin_myplugin_load_js(){
 wp_enqueue_script( 'custom_js', plugins_url( '/js/myplugin.js', __FILE__ ), array('jquery') );
}
add_action('admin_enqueue_scripts', 'admin_myplugin_load_js');

api-wp-css-js

Using above code you can easily Add javascript to wordpress through plugin, website to wp admin panel. Use above code and enjoy!

Add a Comment

Your email address will not be published. Required fields are marked *