WP: Head & Stylesheet

Based on the last few posts, we currently have the following files in our theme’s root directory:

/ob-test
    /style.css
    /index.php
    /header.php
    /footer.php

style.css

/*
Theme Name: OB-TEST
Author: Omkar Bhagat
Version: 1.0
*/

body {
    color: blue;
}

index.php

<?php get_header();
 
while (have_posts()) {
 
    the_post(); ?> 
  
    <h2> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a></h2>
    <p> <?php the_content(); ?> </p>
 
    <?php
}

get_footer(); ?>

header.php

<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
	<p>This is header text</p>

footer.php

<p> This is footer text </p>
</body>
</html>

In the above setup, the code from the stylesheet doesn’t work. The content of the body doesn’t turn blue.

In WordPress, all the head data can be loaded in a different way, by using the wp_head() function. Therefore, our header.php can be changed to the following code:

<!DOCTYPE html>
<html>
<head>
	<?php wp_head(); ?>
</head>
<body>
	<p>This is header text</p>

The function we added takes care of loading scripts, stylesheets, etc but it doesn’t do that automatically. We need to do a couple more changes.

functions.php

The next thing to do there is to create functions.php file with the following code:

<?php 

function ob_site_files() {
	wp_enqueue_style('ob_site_main_styles', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'ob_site_files');

This is the meat and potatoes of this post. We create ob_site_files function that enqueues a new style by using the function wp_enqueue_style and gets the stylesheet via get_stylesheet_uri.

Next we add an action to trigger the load ob_site_files whenever wp_enqueue_scripts is loaded by WordPress.

This makes our stylesheet active. We know this because the body color changes to blue as follows:

And that’d be all in this post. We learned how to load stylesheet correctly in our newly developed WordPress theme.

Leave a comment