WordPress how to enqueue custom script on frontend and avoid enqueueing it on the admin panel

1.4k Views Asked by At

I'm loading a custom script (app-min.js) into a WordPress site. From the site's functions.php:

wp_enqueue_script('app-min', get_template_directory_uri() . '/app/app-min.js', false, 1.0, true);

Works fine on the frontend, but the script is also loaded in the admin panel:

Screenshot, DevTools showing custom script being loaded in WordPress admin panel

Why is this happening and how can I avoid it?

3

There are 3 best solutions below

0
On

You could exclude it from the admin panel by using is_admin condition. So your code would be something like this:

if(!is_admin()){
  wp_enqueue_script('app-min', get_template_directory_uri() . '/app/app-min.js', false, 1.0, true);
}

is_adminDocs

Let me know if it works for you!

0
On

Please use the hook 'wp_enqueue_scripts' to enqueue css and js meant to be specifically used only on frontend. More details on https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/

function theme_enqueue_script() {
    wp_enqueue_script('app-min', get_template_directory_uri() . '/app/app-min.js', false, 1.0, true);
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_script' );
0
On

I'm having the same problem and for some reason the bool is_admin() method did not work, insomuch as the script was still being loaded in the admin. After some digging around, this solution worked for me. FYI I'm adding the script to the footer (last parameter of wp_enqueue_script = false).

function child_enqueue_styles() {
    $is_admin = current_user_can('manage_options');

    if (!$is_admin) {
        wp_enqueue_script( 'child-script', get_stylesheet_directory_uri() . '/js/script.js', array('jquery'),'1.1.6', true );
    }
}
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 15 );

Note that the above solution prevents the script being loaded on the frontend whilst you are logged in. You'll either have to log out or load the front end into an incognito browser window to see the script being loaded.