Add a jQuery function to admin pages

I’d be inclined to just do a one off enqueue and be done with it..

It means you have to manage an additional file(the JS file), but when you’re writing code it’s usually a good idea to create some form of organisation with your files(or at least get into the habit of doing so), ie. javascript/jquery in one folder, css is another, keeping PHP and HTML in your main plugin PHP files.

So my suggestion would be to move the jQuery into a js file, then run an enqueue setting jQuery as a dependancy, but no need to register it for a one off call.

Quite a few choices with regard to hooks, but i’d personally go for..

function yournamespace_enqueue_scripts( $hook ) {

    if( !in_array( $hook, array( 'post.php', 'post-new.php' ) ) )
        return;

    wp_enqueue_script( 
        'your_script_handle',                         // Handle
        plugins_url( '/yourfilename.js', __FILE__ ),  // Path to file
        array( 'jquery' )                             // Dependancies
    );
}
add_action( 'admin_enqueue_scripts', 'yournamespace_enqueue_scripts', 2000 );

Simply adjust the pages you need the enqueue to run on – in the in_array() call.

Leave a Comment