How to use underscore.js in WordPress Admin

I am trying to use underscore in my WordPress Admin. This is what I have done: I enqueue a script in the very end of the page, like so:

function load_admin_scripts() {
  wp_enqueue_script( "my-admin", get_template_directory_uri() . "/assets/scripts/admin.js", array('jquery', 'wp-util'), null, true );
}
add_action('admin_enqueue_scripts', 'load_admin_scripts');

...then in the script file, I am at the moment only trying this:

console.log( jQuery ); // is defined
console.log( underscore ); // ReferenceError: underscore is not defined(…)

Can anyone point me to the solution for this?

Topic underscore wp-enqueue-script wp-admin Wordpress

Category Web


Make sure you enqueue underscore js on theme function.php

/**
 * Proper way to enqueue scripts and styles.
 */
function wpdocs_theme_name_scripts() {
    wp_enqueue_script( 'underscore' );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );

Then you can check underscore version on browser console

console.log(_.VERSION)

Go to you chrome JavaScript console window and write _.VERSION. Then press Enter. It will return you the version of the included Underscore JS. Also it will make sure that Underscore JS is included or enqueued. And Underscore JS is include in WordPress admin by default. You don't need to enqueue it. Just use it as you use any where else.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.