Posted On: October 3, 2024
Here is the translation:
How to Add Your Own JavaScript File to a WordPress Theme
1. Why Is It Smart to Use a Child Theme?
Using a child theme is the best practice when you want to customize a theme because it keeps your customizations safe from any updates to the main theme. The child theme inherits all the functionalities and styling properties of the main theme and allows you to make your own changes without altering the original code of the main theme.2. Creating a Child Theme
If you don’t have a child theme yet, you can create one by following these steps:- Create a Folder for the Child Theme: Go to
wp-content/themes
and create a new folder. Give it a clear name, e.g.,my-child-theme
. - Create a style.css File: Add a
style.css
file to the new folder with the following content:
/*
Theme Name: My Child Theme
Template: name-of-main-theme
*/
- Create a functions.php File: In the same folder, create a
functions.php
file with the following content:
<?php
// Inherit styles from the main theme
function my_child_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'my_child_theme_enqueue_styles' );
?>
3. Adding a Custom JavaScript File
Now that you have the child theme ready, you can add your custom JavaScript file.- Create a JavaScript File: Create a
js
folder inside your child theme folder (/wp-content/themes/my-child-theme/js/custom.js
). You can add your JavaScript code to this file. - Add JavaScript Code: In the
custom.js
file, add your code. For example, the following code changes the background color of the page body when the document is ready:
jQuery(document).ready(function($) {
$('body').css('background-color', '#f0f0f0');
});
- Enqueue the JavaScript File in functions.php: Add the following code to your child theme’s
functions.php
file to enqueue the new JavaScript file:
<?php
// Inherit styles from the main theme
function my_child_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'my_child_theme_enqueue_styles' );
// Add custom JavaScript file
function my_child_theme_enqueue_scripts() {
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), null, true );
}
add_action( 'wp_enqueue_scripts', 'my_child_theme_enqueue_scripts' );
?>