Including CSS and JavaScript in WordPress – The Right Way

In WordPress, there are a few different ways to include CSS and JavaScript in your site. Here are some options:

  1. Enqueueing Scripts and Stylesheets: This is the recommended method for adding CSS and JavaScript in WordPress. You can enqueue your scripts and stylesheets using the wp_enqueue_script() and wp_enqueue_style() functions, respectively. These functions ensure that your scripts and stylesheets are loaded in the correct order and only once.

Here is an example of how to enqueue a stylesheet:

php
function mytheme_enqueue_styles() {
wp_enqueue_style( 'mytheme-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_styles' );

And here is an example of how to enqueue a script:

php
function mytheme_enqueue_scripts() {
wp_enqueue_script( 'mytheme-script', get_template_directory_uri() . '/js/my-script.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts' );
  1. Hardcoding Scripts and Stylesheets: You can also include CSS and JavaScript by hardcoding them into your theme’s header.php or footer.php files. However, this is not recommended as it can cause issues with caching and can be more difficult to maintain.
  2. Using a Plugin: There are also plugins available that can help you add CSS and JavaScript to your site. However, it’s important to choose a reputable plugin and be careful not to overload your site with too many plugins.

In general, it’s best to use the enqueueing method as it ensures that your scripts and stylesheets are loaded in the correct order and only once.