Add custom javascript and CSS to WordPress admin

A conceptual example of how you could add css or javascript to your ”edit post” page in the WordPress dashboard.
I included an example of how you can ”send parameters” to the javascript file.

<?php
class MyClass {
	function admin_init() {
		wp_register_style( 'my_css', get_stylesheet_directory_uri() . 
			'/css/my_class.css' );
		wp_register_script( 'my_js', get_stylesheet_directory_uri() . 
			'/js/my_class.js', 'jquery', '1.0.6', true );
	}
 
	function enqueue_css() {
		wp_enqueue_style( 'my_css' );
	}
 
	function enqueue_js() {
		wp_enqueue_script( 'my_js' );
 
		// Add current post id as a javascript variable.
		global $post;
		$current_id = empty( $post ) ? '' : $post->ID;
		$my_params = array(
		  'postid' => $current_id,
		);
		wp_localize_script( 'my_js', 'MyParams', $my_params );
	}
}
 
if ( class_exists( "MyClass" ) ) 
	$my_class = new MyClass();
else
	error_log( "MyClass missing" );
 
add_action( 'admin_init', array(&$my_class, 'admin_init') );
add_action( 'admin_print_styles-post.php', array(&$my_class, 'enqueue_css') );
add_action( 'admin_print_scripts-post.php', array(&$my_class, 'enqueue_js') );

Kommentera

E-postadressen publiceras inte. Obligatoriska fält är märkta *