Structuring the theme
I would like to have different directories for my CSS and JavaScript, so let’s create them. Remember that we start from our installation directory.
cd /var/www/html
cd wp-content/themes/my-first-theme
mkdir js
mkdir css
touch css/my-first-theme.css
touch js/my-first-theme.js
After doing this, we have created the directories css and js containing the (empty) files my-first-theme.css and my-first-theme.js respectively. We will insert content in these files later. For now, we need to somehow “tell” WordPress to use these files. We do this in the file functions.php.
The file functions.php
WordPress looks for this file, expecting code that will be executed before the rest of the WP code.
touch functions.php
We use this file to instruct WordPress to use our new css and javascript files. We insert the following code snippet in the functions.php file.
<?php
//create a callback function to be called on some wordpress action
function my_first_theme_enqueue_scripts(){
//add a stylesheet file to the queue
wp_enqueue_style('customstyle',get_template_directory_uri() . '/css/my-first-theme.css',
array(),'1.0.0','all');
//add a stylesheet file to the queue
wp_enqueue_script('customjs',get_template_directory_uri() . '/js/my-first-theme.js',
array(),'1.0.0',true);
}
/*
link the wp_enqeue_scripts hook to our callback.
whenever WP executes the "wp_encueue_scripts" it will call our
notice that "wp_enqueue_scripts" is used for both scripts and styles
*/
add_action('wp_enqueue_scripts','my_first_theme_enqueue_scripts');
//php close tag ommited on purpouse
Activating the changes
For the changes to become active, we need to instruct WP where the queued content should be shown.
Insert queued css
We modify the file header.php. We add a PHP code block after the title tag and call the wp_head() hook.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>my-first-theme</title>
<?php
/*Insert qeued content (css) here.
See functions.php*/
wp_head(); ?>
</head>
<body>
Insert queued JavaScript
We want the JavaScript at the end of the HTML content.
Modify the file footer.php and insert a PHP code-block just before the closing tag for the body. In this code-block, we call the wp_footer() hook.
<footer>
this is my footer
</footer>
<?php
/*Insert queued content (javascript) here.
See functions.pho
*/
wp_footer(); ?>
</body>
</html>