The correct way to include JavaScript and CSS in my WordPress Themes

I’m trying to build my own WordPress theme using the correct ways. But…

The first trouble that I found was how to add css and js “using the correct way”.

I found severals tutorials how to do it. e.x: http://code.tutsplus.com/tutorials/loading-css-into-wordpress-the-right-way–cms-20402 (this is from “30-Jun-2014”) and this one http://code.tutsplus.com/articles/how-to-include-javascript-and-css-in-your-wordpress-themes-and-plugins–wp-24321 (this is from “14-Feb-2012”) They explain the same way.

Also I took a look of the theme “twentyfifteen” and has another different way.

Let me explain it with code:

If I follow the two tutorials from “tutsplus” my code to add css and js looks like this:

<?php

function scripts() {
    wp_register_style(
        'bootstrap', 
        get_template_directory_uri() . '/css/bootstrap.min.css',
        '3.3.1',
    );
    wp_enqueue_style( 'bootstrap' );
}

function mytheme_enqueue_style() {
    wp_enqueue_style( 'bootstrap', get_stylesheet_uri() ); 
    }
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_style' );

?>

If I follow the way how is made in the “twentyfifteen” theme my code looks like this:

<?php
function scripts() {

    // Load bootstrap.
    wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', '3.3.1' );

add_action( 'wp_enqueue_scripts', 'scripts' );
?>

I like this last one because is less code and more clear but I don’t know if “the correct way”.

Of course I read the CODEX but for me it’s not clear of all because there are example with both ways. And also I found similar questions but don’t answers my question. Including jQuery and JavaScript files the correct way and What’s the correct way to include files in WordPress TwentyTen theme with it’s own jquery scripts and css?

I hope some expert or not expert on WP can help me.

Thank you! 🙂

2 Answers
2

Pretty straightforward answer is both are the correct. In first method you are breaking down the process in two steps. That is needed in case you want to register some scripts but want to load them conditionally at some later time. For example you may want to load some script only when some second script requires this first script. In this case you can simply register your first script and while enqueuing the second script you can specify the handle of your first script as a dependency.

More clear way of explaining this is think jquery. WordPress registers it by default for you. If you want to use jquery in your site you can either simply enqueue it or enqueue another script which has dependency on jQuery.

If you straight away want to use your scripts then the other method is quite short and clean.

Leave a Comment