1

Different pages often need different set of scripts and styles for them.

I use functions.php and construction like this to load scripts and styles:

function load_assets() {
   wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/styles.css');
   wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js');
}
add_action( 'wp_enqueue_scripts', 'load_assets' );

I know I can put some condition here like this:

is_page()

but is there a better way?

Suggestion:

Can wp_register_script() be used to target specific pages?

4
  • 1
    I don't know any better way. Why does the is_page() bothers you ?
    – Sladix
    Commented Dec 16, 2015 at 8:31
  • It doesn't really bother me, but I don't like that if you need to enqueue custom scripts for 'about' page you need to go to dashboard, look this page id and yeah...
    – Boykodev
    Commented Dec 16, 2015 at 8:38
  • 1
    is_page also accepts a title or slug. there's also is_page_template that lets you target php template files.
    – Milo
    Commented Dec 16, 2015 at 8:40
  • Ok, I'll give it a try.
    – Boykodev
    Commented Dec 16, 2015 at 8:42

2 Answers 2

3

Yes, you may add conditional tags to the wp_enqueue_scripts action. See the examples below:

function load_assets() {
   wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/styles.css');

   // loads on any 'page' post type
   if( is_page() ){
       wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js');
   }

   // only loads on the page with a slug of 'home'
   if( is_page('home') ){
       wp_enqueue_script('home-js', get_template_directory_uri() . '/js/home.js');
   }


}
add_action( 'wp_enqueue_scripts', 'load_assets' );

For other examples of is_page() usage, see the codex page: https://codex.wordpress.org/Function_Reference/is_page

2
  • Yeah, that's what I was told in comments above. Thanks for detailed example.
    – Boykodev
    Commented Dec 16, 2015 at 9:07
  • No problem ! Would you mind accepting the answer if it is solves your question? Commented Dec 16, 2015 at 9:09
1

For admin you can do in this way.

function load_assets( $hook ) {

    global $post;

    if ( $hook == 'post-new.php' || $hook == 'post.php' ) {
        // enqueue here
    }
}
add_action( 'admin_enqueue_scripts', 'load_assets', 10, 1 );
1
  • You mean it will work only for admin? It's something, but I need all users solution.
    – Boykodev
    Commented Dec 16, 2015 at 8:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.