The right way to include css / js files in wordpress

  • admin
  • Tag 1
    Tag 2
    Tag 3
    Tag 4

    As a professional web developer, I see a lot of code in a day. A LOT!. Whether it be on one of the numerous forums I use daily (Stack overflow, WordPress codex, github etc) or working on a project another developer started, it’s safe to say that each and every person has their own unique way of getting things done. Sometimes it’s innovative and interesting, and sometimes it’s downright inefficient and even insecure or possibly dangerous. WordPress is awesome, because it gives us developers the tools to do things the right way.

    Here’s the very simple (and correct) way to enqueue javascript and css files in WordPress. Please keep in mind, that this method CAN be used in either themes or plugins interchangeably, you just have to make sure you are pointing to the right folder.

    So to get started, first we have to hook into the action that wordpress uses to register and enqueue scripts / styles. We do that by creating an action hook, and a function to accompany the hook like so (You can put the all of the following code in your themes functions.php file):

        add_action('wp_enqueue_scripts', 'theme_queue_style');
        function theme_queue_style () {
            // This is where you'll add the register and enqueue commands //

    Once that’s done, you add the register and enqueue commands to the function like so:

        function theme_queue_style () {
            // This is where you'll add the register and enqueue commands //
            // Please note, get_stylesheet_directory_uri() refers to a child themes parent directory.
            // If you're editing a parent theme directly, then you'd use get_template_directory_uri() instead.
            // If you're working on a plugin, you can use plugins_url() to get the parent directory of your plugin.
            wp_register_style('skill_logos', get_stylesheet_directory_uri() . '/css/logos.css');
            // You can also register scripts in here, following the same structure as css files //
            wp_register_script('anarchy_float_menu_js', get_stylesheet_directory_uri() . '/js/custom.js');

    Of course, you can also add some conditional checks, such as is_admin() or is_home() to control if and when your files are enqueued. Not only does this method allow you to easily hook, and unhook files as you need them, it’s also much cleaner than cramming them into the header file.

    Leave a comment

  • (required)