Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom javascript to WordPress Admin?

I want to add some custom jquery code to the Edit Post page, something really simple like showing a div when someone presses Publish.

The only restriction is that I want to achieve this through the use of a plugin, not hacking the admin template files.

I've tried echoing some script tags using some actions but it doesn't seem to be the way.

like image 361
Nacho Avatar asked Jul 24 '10 21:07

Nacho


People also ask

Can you add custom JavaScript in WordPress?

You can add custom JavaScript to your WordPress site either by using a plugin or by editing your theme or child theme's functions. php file. Using a plugin is the recommended technique if you don't want to edit your source files, as these plugins ensure that your custom scripts load in the right order.

Can you edit JavaScript in WordPress?

In case you're unfamiliar, WordPress ships with a built-in editor that enables you to modify your theme's files online. In the Theme Editor, you can access the PHP, CSS, JavaScript, and all other development-related files that make up your theme.


2 Answers

Use the admin_enqueue_scripts action and the wp_enqueue_script method to add custom scripts to the admin interface.

This assumes that you have myscript.js in your plugin folder. Change accordingly. The my_custom_script handle should be unique for your module and script.

function my_enqueue($hook) {     // Only add to the edit.php admin page.     // See WP docs.     if ('edit.php' !== $hook) {         return;     }     wp_enqueue_script('my_custom_script', plugin_dir_url(__FILE__) . '/myscript.js'); }  add_action('admin_enqueue_scripts', 'my_enqueue'); 
like image 184
Tim Avatar answered Oct 04 '22 19:10

Tim


There is a snippet for Your functions.php file :

function custom_admin_js() {     $url = get_bloginfo('template_directory') . '/js/wp-admin.js';     echo '"<script type="text/javascript" src="'. $url . '"></script>"'; } add_action('admin_footer', 'custom_admin_js'); 

Works fine on Wordpress 3.2.1.

like image 42
Fedir RYKHTIK Avatar answered Oct 04 '22 19:10

Fedir RYKHTIK