How to add CSS and JavaScript the correct way in WordPress?

Never add <link> or <script> tags directly in header.php. Register them with enqueue functions, so WordPress can manage the order, the dependencies and the duplicates.

add_action( 'wp_enqueue_scripts', function () {
	wp_enqueue_style( 'my-style', get_stylesheet_uri(), array(), '1.0' );
	wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/main.js', array( 'jquery' ), '1.0', true );
} );
  • The hook for the front end is wp_enqueue_scripts. For the dashboard it is admin_enqueue_scripts.
  • The 3rd parameter is the list of dependencies. The 4th is the version (cache busting). The last parameter of the script is true to load it in the footer.
  • Use wp_add_inline_script() to pass PHP data to your script.

Read the tested example in Enqueue Scripts and Styles.


Learn more about the similar topics:
Tutorials
WordPress Themes
WordPress Top Theme List
WordPress Theme Files and Functions
WordPress Template Hierarchy
WordPress Enqueue Scripts and Styles
WordPress Loop
WordPress WP_Query Class
Exercises & Assignments
Build and activate a minimal classic theme
Show the three latest posts with WP_Query
Load a stylesheet with wp_enqueue_style and a version
Show a message only on the front page
Create a child theme which changes the footer
Interview Questions & Answers
What is a WordPress theme?
What are commonly used WordPress theme functions?
Which function is used to get the home URL in WordPress?
Which are the necessary files for a WordPress theme?
What is the use of the wp_head() function in WordPress?
What is the WordPress Loop?
What is the difference between is_home() and is_front_page()?