1

I'm having difficult to load the path correctly in an 'enqueue' function.

What I am trying to achieve is to load a specific CSS stylesheet on a specific page...

The below works by adding the path to the markup on the correct template - but - the path is wrong...

 add_action('wp_enqueue_scripts','homepage');
  function homepage(){
    if ( is_page_template('page-home.php') ) {
      wp_enqueue_style('home-css', array(), '1.0.0', true );
      get_template_directory_uri() . '/css/flags.min.css',
    }
  }

The reason is because (I believe) the path is not set correctly to find the appropriate css folder...

The php is therefore missing this line:

get_template_directory_uri() . '/css/flags.min.css',

My question is - how do I add this line that locates the theme css folder? I tried the below but it did NOT work...

 add_action('wp_enqueue_scripts','homepage');
  function homepage(){
   if ( is_page_template('page-home.php') ) {
      wp_enqueue_style('home-css', array(), '1.0.0', true );
      get_template_directory_uri() . '/css/flags.min.css',
    }
   }

1 Answer 1

3

The second parameter of wp_enqueue_style() is an optional path.You are passing an empty array, which will enqueue nothing.

get_template_directory_uri() retrieves the current theme's root URI, which you can use in wp_enqueue_style():

 add_action('wp_enqueue_scripts','homepage');
  function homepage(){
   if ( is_page_template('page-home.php') ) {
      wp_enqueue_style('home-css', get_template_directory_uri() . '/css/flags.min.css', '1.0.0', true );
    }
   }

I mentioned "Optional", since there is also another way to use wp_enqueue_style. In this method, you can first use wp_register_style, and then enqueue it:

wp_register_style( 'home-css', get_template_directory_uri() . '/css/flags.min.css' );
wp_enqueue_style('home-css');

The same works for wp_enqueue_script().

Based on using parent theme or child, you might also want to take a look into get_stylesheet_directory_uri() too.

3
  • OK cool - thanks for that - also - I've made an error with calling wp_enqueue_scripts? The file I am trying to call is .css so I guess it should be wp_enqueue_styles?
    – Henry
    Commented Aug 7, 2017 at 5:49
  • There is no such function as wp_enqueue_styles(). The name "wp_enqueue_scripts" might be misleading, since it enqueues both styles and scripts.
    – Johansson
    Commented Aug 7, 2017 at 5:51
  • My pleasure Henry :)
    – Johansson
    Commented Aug 7, 2017 at 5:58

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.