How to run a external JavaScript file on wp-admin if admin, and other if normal user?

I’m new to WordPress plugins, and I’m trying to load a external JS/jQuery file with some scripts I need. It needs to run in the wp-admin page (not just once when activated). There is a JS file for a common user and another one for the admin.

function wp_ui_activation() {
}

register_activation_hook(__FILE__, 'wp_ui_activation');

function wp_ui_deactivation() {
}

register_deactivation_hook(__FILE__, 'wp_ui_deactivation');

add_action('wp_enqueue_scripts', 'wp_ui_scripts');

function wp_ui_scripts() {  
    wp_enqueue_script('jquery'); //add jquery

    if (!is_admin()) { // it's not admin
        wp_register_script('custom_script', plugins_url('assets/js/custom_script.js', __FILE__),array('jquery')); //register custom_script
        wp_enqueue_script('custom_script'); //add custom_script
    }

    if(is_admin()){ // it's admin
        wp_register_script('custom_admin_script', plugins_url('assets/js/custom_admin_script.js', __FILE__),array('jquery')); //registra custom_admin_script
        wp_enqueue_script('custom_admin_script'); //add custom_admin_script
    }       
}

All that resides inside the JS file is a jQuery(function() {alert("admin")}); and a jQuery(function() {alert("no-admin")}); but none of them shows up…

Read More

What am I missing?

Related posts

1 comment

  1. You need to register/enqueue your admin scripts on admin_enqueue_scripts, not on wp_enqueue_scripts. wp_enqueue_scripts is a front end hook. It won’t run on the admin pages.

    Secondly, is_admin() just checks whether the page is an admin page, not whether the user is an administrator. To check whether the user is an administrator use:

    $current_user = wp_get_current_user();
    if (user_can( $current_user, 'administrator' )) {
      // user is an admin
    }
    

    Reference:

    http://codex.wordpress.org/Function_Reference/user_can
    http://codex.wordpress.org/Function_Reference/wp_get_current_user

Comments are closed.