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 isadmin_enqueue_scripts. - The 3rd parameter is the list of dependencies. The 4th is the version (cache busting). The last parameter of the script is
trueto 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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |