wordpress-theme

WordPress Themes, How to Build Them.

By Rasyue | On September 11, 2020

WordPress Themes is part of WordPress which is a content management system written in PHP and paired with a MySQL or MariaDB database. WordPress use a plugin architecture and a template system which is referred to as Theme.

In this article, I will be covering all the basic and advanced stuff that you need to know to create your own themes today. Whether you want to sell it or use it as your own, it is all up to you.

Let’s get busy, shall we?

Introduction

To start building your own WordPress Themes, first make sure you already have it running locally on your computer. If you don’t, go here to get your copy of WordPress.

Once you get your WordPress setup locally, open up your IDE and go to your WordPress, for mine, it will be something like this, C:/xampp/htdocs/wordpress/wp-content/themes, now inside your themes folder create a new folder and name it as you like, I will name mine as Rasyue. So the final theme project folder will be C:/xampp/htdocs/wordpress/wp-content/themes/rasyue.

wordpress-theme

If you notice, there are other themes that WordPress comes with in the themes folder. We are going to build similar thing.

WordPress Themes Basic Files

Two files that are essential to create your WordPress Themes are index.php and style.css.

Now create these 2 files in your project theme directory. Open up your style.css and paste the following lines.

/*
Theme Name: Rasyue
Theme URI: 
Author: The Rasyue Team
Author URI: 
Description: Our very own wordpress theme made with love
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: rasyue
Tags: rasyue, mobile-friendly, responsive

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.

*/

Now, open up your index.php and paste the following lines.

<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package WordPress
 * @subpackage Rasyue
 * 
 */

get_header();
?>

	<div id="main">
		
	</div>

<?php
get_footer();

If you notice, in our index.php, we used two WordPress built-in functions which are get_header() and get_footer(). Both simply means to get the respective file which are header.php and footer.php. So go ahead and create the two files.

wp-directory

Now, if you go to your WordPress admin panel, Appearance > Themes, you can see that your theme is now registered in the list. Go ahead and activate it.

After you have activated your theme, go to your home page.

wp-home-page

You should get a blank white page. That is because we haven’t really write any HTML. What we did was creating the basic files for our theme to actually work.

Setup The Look and Feels of Our Theme

Now, before we go further into our Theme Development, let’s write some HTML for our basic files, which are the index.php, header.php and footer.php. Please note that these is just the basic HTML and I will leave you with your imagination and creativity to design your own look and feels.

Open up your header.php and paste the followings.

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
	<head>
		<title><?php bloginfo( 'name' ); the_title( ' | ' , '');  ?></title>
		<meta name="description" content="<?php bloginfo( 'description' ); ?>">
		<meta charset="<?php bloginfo( 'charset' ); ?>">
		<meta name="viewport" content="width=device-width, initial-scale=1">
	
		<?php wp_head(); ?>
	</head>

<body <?php body_class(); ?>>
	
<nav class="navbar navbar-expand-lg text-dark">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
    aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
  </div>
</nav>
	

Just FYI, if you have any Google Fonts to include, you can include the <link> inside this header.php. We will see how do we add Bootstrap to our project later on.

Now, open up your footer.php and paste the followings.

<?php
/**
 * The template for displaying the footer
 *
 * Contains the closing of the #content div and all content after.
 */

?>
<!-- Footer -->
<footer class="page-footer font-small blue pt-4">

  <!-- Footer Links -->
  <div class="container-fluid text-center text-md-left">

    <!-- Grid row -->
    <div class="row">

      <!-- Grid column -->
      <div class="col-md-6 mt-md-0 mt-3">

        <!-- Content -->
        <h5 class="text-uppercase">Footer Content</h5>
        <p>Here you can use rows and columns to organize your footer content.</p>

      </div>
      <!-- Grid column -->

      <hr class="clearfix w-100 d-md-none pb-3">

      <!-- Grid column -->
      <div class="col-md-3 mb-md-0 mb-3">

        <!-- Links -->
        <h5 class="text-uppercase">Links</h5>

        <ul class="list-unstyled">
          <li>
            <a href="#!">Link 1</a>
          </li>
          <li>
            <a href="#!">Link 2</a>
          </li>
          <li>
            <a href="#!">Link 3</a>
          </li>
          <li>
            <a href="#!">Link 4</a>
          </li>
        </ul>

      </div>
      <!-- Grid column -->

      <!-- Grid column -->
      <div class="col-md-3 mb-md-0 mb-3">

        <!-- Links -->
        <h5 class="text-uppercase">Links</h5>

        <ul class="list-unstyled">
          <li>
            <a href="#!">Link 1</a>
          </li>
          <li>
            <a href="#!">Link 2</a>
          </li>
          <li>
            <a href="#!">Link 3</a>
          </li>
          <li>
            <a href="#!">Link 4</a>
          </li>
        </ul>

      </div>
      <!-- Grid column -->

    </div>
    <!-- Grid row -->

  </div>
  <!-- Footer Links -->

</footer>
<!-- Footer -->

<?php wp_footer(); ?>

</body>
</html>

Open up your index.php and paste the following.

<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package WordPress
 * @subpackage Rasyue
 * @since 1.0.0
 */

get_header();
?>

	<div style= 'min-height: 700px;'>

        <h1>Hello World!</h1>
        <div class = 'mt-5'>
            <h2>Welcome to my WordPress site!</h2>
        </div>
	</div>

<?php
get_footer();

And with that, if you refresh your homepage, it’s not gonna look pretty, that’s because we haven’t load our Bootstrap yet. Let’s load it up now.

Adding Bootstrap to WordPress

Now, we are going to create a new file and name it as functions.php. Please name the file exactly like I named it because this file is important in WordPress if you have any code you want to write and get it to work in your WordPress site.

Open your functions.php and paste the followings:

<?php


function rasyue_scripts() {
    wp_enqueue_style('bootstrap4', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css');
    wp_enqueue_script( 'boot1','https://code.jquery.com/jquery-3.3.1.slim.min.js', array( 'jquery' ),'',true );
    wp_enqueue_script( 'boot2','https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js', array( 'jquery' ),'',true );
    wp_enqueue_script( 'boot3','https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js', array( 'jquery' ),'',true );
}
add_action( 'wp_enqueue_scripts', 'rasyue_scripts' );

?>

Okay! That’s all you need for now, refresh your homepage now and it will look decent.

wp-hello-world

Next Step For Your Theme Development

Now, WordPress is a really awesome CMS which mean from the Admin Panel, you can easily create your own pages, posts, tags, categories, sidebar, nav-menu(for both header and footer) and lots more.

This means that we can dynamically create any pages, posts, categories etc from the Admin Panel and from our Themes file we can fetch it and use it to display in our theme.

Meaning we don’t have to frequently go to our source code and create new file whenever we want to create a new page.

So in the following sections, I will try to cover all the stuff that you need to know to further continue your theme development.

Registering Nav Menu

Okay, first of all, let’s learn how to register our nav-menu so that whenever we change our nav-menu from our WP admin panel, it will dynamically be fetched and display on our WP site.

Go to your functions.php and paste the following, remember not to overwrite anything that is already in your functions.php

function custom_register_nav_menu() {
	register_nav_menu( 'primary', 'Header Navigation Menu' );
}
add_action( 'after_setup_theme', 'custom_register_nav_menu' );

And with that, you can go to your admin panel and you Menus under Appearance

wp-nav-menu
WP Nav Menu

From the nav menu panel, you can add anything from your pages, posts, categories and even custom links.

However, remember to manage the location of your nav menu, got to the tab Manage Locations and register the Primary Menu as the Header Navigation Menu

wp-header-place

Now, how do we fetch this from the WP core and display it in our navbar? Remember in our header.php that we already hav a navbar with few nav-items but we hard-coded.

What we want to do is to make those nav-items to appears dynamically, meaning whenever we change it from the wp admin nav menu, our nav items on our site will also change.

Open your header.php and paste the followings

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
	<head>
		<title><?php bloginfo( 'name' ); the_title( ' | ' , '');  ?></title>
		<meta name="description" content="<?php bloginfo( 'description' ); ?>">
		<meta charset="<?php bloginfo( 'charset' ); ?>">
		<meta name="viewport" content="width=device-width, initial-scale=1">
	
		<?php wp_head(); ?>
	</head>

<body <?php body_class(); ?>>
	
<nav class="navbar navbar-expand-lg text-dark">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
    aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <?php
        wp_nav_menu( array(
            'theme_location' => 'primary',
            'container' => false,
            'menu_class' => 'navbar-nav',
            
        ) );	
    ?>
  </div>
</nav>
	

When you refresh your homepage, you will have something like this.

front-page-php

Now with this, you can dynamically change your nav-items from your admin panel and it will be automatically displayed. Great job so far for you!

FYI, you can register another nav-menu for your footer, just go to your functions.php, duplicate the function to register the nav-menu, just remember to change the text from primary to primary-footer or whatever you want and the rest of process is the same. You just have to change your footer.php.

On to the next section lads!

Front Page

By default, WordPress will look for index.php in our theme directory to serve as our landing page or our Front Page.

You can overwrite this behaviour by creating a file name front-page.php. Go ahead and create a new file name front-page.php and write any HTML in it.

It should overwrite our index.php which we already have our navbar and footer.

If it doesn’t go to your admin panel, go to Settings > Reading and set your homepage to Home page. Create a Home page if you haven’t done so.

So, I’ve created a front-page.php and have the following codes.

<?php
/**
 * The main template file
 *
 */
get_header();
?>
	<div class="content-area homepage-div" style ='min-height: 700px;'>
		<h1>Hello World!</h1>
        <h2>Front Page</h2>
	</div>

<?php
get_footer();

?>
sidebar-page

Moving forward, we will treat front-page.php as our index.php. You can leave out your index.php from now on.

Let’s look at how we can add a sidebar.

Add Sidebar

WordPress has a feature that is knows as sidebar that we can dynamically build from the admin panel and then call it through WordPress built-in function and use it in our theme.

But first we have to register it in our functions.php. Open up your functions.php and add the following at the bottom.

add_action( 'widgets_init', 'custom_register_sidebars' );
function custom_register_sidebars() {
    /* Register the 'primary' sidebar. */
    register_sidebar(
        array(
            'id'            => 'primary',
            'name'          => __( 'Primary Sidebar' ),
            'description'   => __( 'Primary sidebar.' ),
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
            'after_widget'  => '</div>',
            'before_title'  => '<h3 class="widget-title">',
            'after_title'   => '</h3>',
		)
	);
	
	register_sidebar(
        array(
            'id'            => 'secondary',
            'name'          => __( 'Secondary Sidebar' ),
            'description'   => __( 'Secondary sidebar.' ),
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
            'after_widget'  => '</div>',
            'before_title'  => '<h3 class="widget-title">',
            'after_title'   => '</h3>',
        )
    );
    /* Repeat register_sidebar() code for additional sidebars. */
}

Now create a new file which will serves as a template for your sidebar, this determine how your sidebar will appear. Create a file name sidebar-primary.php and paste the followings.

<div id="sidebar-primary" class="sidebar border p-3 mb-3" style = 'box-shadow: 5px 5px;'>
    <?php dynamic_sidebar( 'primary' ); ?>
</div>

Go back to your front-page.php and paste the followings.

<?php
/**
 * The main template file
 *
 */
get_header();
?>
	<div class="content-area homepage-div" >
		<h1>Hello World!</h1>
       

        <div class = 'row w-100'>
            <div class = 'col-md-9'>
            </div>
            <div class = 'col-md-3'>
                <?php get_sidebar( 'primary' ); ?>
            </div>
        </div>
	</div>
    
<?php
get_footer();

?>

Go back to your admin panel, Appearance > Widgets and add some widgets into your sidebar. You should have something like this now.

side-bar
Front-page with sidebar

Blog Loop Section

By now, we already have a front-page with navbar and footer. You probably want to create more pages from your admin-panel and then add it to your nav-menu from your admin-panel as well.

Now, let’s look at how we can call our posts loop so we can display it in our front-page. Remember this posts loop is just a PHP code that we can call in any of our pages, of course right now we only have our front-page.php to work with, but I will show you later on how to create a unique template for each page.

But first, let’s look at how do we call our blog posts. Go to your front-page.php and paste the followings.

<?php
/**
 * The main template file
 *
 */
get_header();
?>
	<div class="content-area homepage-div" >
		<h1>Hello World!</h1>
       

        <div class = 'row w-100'>
            <div class = 'col-md-9'>

                <?php 
                    query_posts( 
                        array(
                            'posts_per_page' => 7,
                        )
                    );
                    
                    if( have_posts() ):
                        
                        while( have_posts() ): the_post(); 

                                get_template_part( 'templates/template-blog', get_post_format() );
                        
                        endwhile;
                        
                    endif;
                    
                ?>  
            </div>
            <div class = 'col-md-3'>
                <?php get_sidebar( 'primary' ); ?>
            </div>
        </div>
	</div>
    
<?php
get_footer();

?>

We added our loop which starts with the query_posts() and we display each of our blog posts until there’s nothing left to display before ending the loop. Each of our blog post, we can specify a template which is how we can design each of our blog to display,

But remember this is just the part where we display the list of posts. We will need another file when we click on the blog post so we can read the content of our post.

Single.php Page

Now go ahead and create a file name single.php . This file will serve as a template whenever you want to view your blog posts or if a user wants to read your blog posts and the user clicks on it, this single.php will serve as a template to display the content of your post.

Open your single.php and paste the followings.

<?php
 /*
	
@package rasyuetheme
*/

get_header(); ?>
	<div id="primary" class="content-area">
		
        <div class = "row w-100 pt-5 m-0">			
         
            <div class = 'col-md-10'>
                <header class="entry-header text-center">
                    <div class = 'single-header'>
                        <?php if (has_post_thumbnail()) : ?>                        
                            <?php the_post_thumbnail(); ?>
                        <?php endif; ?>
                        <div class="single-header-title" >
                            <?php the_title( '<h1>', '</h1>'); ?>
                            <p class="details">By <?php echo get_the_author() ?> | On <?php echo get_the_date('F j, Y'); ?></p>
                        </div>
                    </div>					
                </header>
            </div>
            <div>
                <?php 
							
                    if( have_posts() ): ?>
                        
                <?php	while( have_posts() ): the_post(); ?>
                            
                <?php	get_template_part( 'templates/single', get_post_format() ); ?>
                                                                                                            
                        
                <?php	endwhile; ?>
                        
                <?php	endif; ?>
            </div>
        </div>	
	</div>
	
<?php get_footer(); ?>

Now create a file in templates/single.php to serve as a template to display your post content. In your templates/single.php, paste the followings.

<?php
/*
@package rasyuetheme
-- Single Post Template
*/
?>
	

    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <?php
                    // WordPress built-in function to fetch your post content
                     the_content(); 

        ?>
    </article>

Okay, I feel like I have to emphasise this part, the things that we have coded up till now is without a pretty design, what I wanted to do is to show you how to dynamically build your themes.

You are free to design your theme however you like, but remember to not delete or remove all the WordPress built-in function that I have shown previously.

WordPress Themes Page Template

From the WP Admin Panel, you can create as many pages as you like and you are also able to customise & style each and every pages.

Create a php file and name it however you like but for the sake of standardisation, try to name it close to your page name. For example template-about-us.php or maybe about-us-template.php

Inside the template file, copy the following, remember, the top part comment is the most important part.

<?php
/*
Template Name: About Us
*/
?>
<?php
get_header();
?>
<!--
Go Crazy with your HTML here
-->

<?php
get_footer();

WordPress Theme 404 Page

You are able to customise the 404/Page not found that you want to show to the user in case if user try to go to an URL that does not exists on your site.

Simple create a file and name it 404.php. You may copy the below and write any HTML for the content.

<?php
/**
 * The template for displaying 404 pages (not found)
 *
 */

get_header();
?>

	<!--
 Write any HTML here as a content to show to the User. Go crazy~
-->

<?php
get_footer();

Search Page

WordPress has its built-in search function that you can apply in your WordPress themes.

You can create a search box simply using the below form and the search page that display the search results can also be customised to your heart content.

Search form.

<!-- This is the search form that you may put anyway in your theme-->
<form id = 'searchForm' action="/" method = 'GET' class="entypo-search">
				
					<div class="input-container">						
						<input id="search"  class="search-input" placeholder="Search" type="search" name ='s'>
					</div>
				</form>  

Create a file name search.php and copy the below codes.

<?php get_header(); ?>

<div>
        <?php
            $s=get_search_query();
            $args = array(
                        's' =>$s
                    );
            // The Query
            $the_query = new WP_Query( $args );


            if( $the_query->have_posts() ):

            while( have_posts() ): the_post(); 

                    get_template_part( 'template-parts/search', get_post_format() );

            endwhile;

            else:
                echo '<h3>Sorry, there is no related post to your search query.</h3>';
                echo '<a href = "/">Go Back to Home..</a>';
            endif;

            
        ?>
</div>        

<?php get_footer(); ?>

If you notice in the while loop, the get_template_part() has 2 args and you can pass in the template for your search as the first arg. This template is where you can control how your search result looks like, typically how your posts look like. Go ahead and create your search template, in my case I created template-parts/search.php

In the template-parts/search.php (don’t get confused though, the search.php is inside the template-parts folder), paste the below codes.

<?php

/*
@package rasyue
Search Result Format
*/

?>




<article>
    <div>
        <a href="<?php the_permalink(); ?>" title="<?php the_title() ?>"  id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        
            <figure class = 'search-img'>
            <?php if( has_post_thumbnail() ): ?>
            <?php the_post_thumbnail(); ?>    
            <?php endif; ?>
            
            </figure>
            <div class = 'rasyue-text' >
                <?php the_title('<h1>', '</h1>'); ?>
             
                <p>
                    <?php 
                        global $post;
                        $categories = get_the_category($post->ID);
                        echo 'In '.$categories[0]->cat_name. ' | By '. get_the_author();
                  
                    ?>
                </p>
            </div>      
            
        </a>
    </div>
</article>

WordPress Theme Tag & Category pages

Two things that you probably have already know about WordPress is that you can specify tags for each blog post you created and category to assign the blog post.

With category.php and tag.php you can customise the looks and feels to show the category and tags associated to your blog posts.

In category.php, paste the below codes.

<?php
/**
 * The template for displaying category page
 */

get_header();
?>
<div id="primary" class="content-area">
	<main id="main" class="site-main p-5">
		<div class = "m-0 main">  
			<?php 
			
				if( have_posts() ):
					
					while( have_posts() ): the_post(); 
					
							get_template_part( 'template-parts/content', get_post_format() );
					
					endwhile;
					
				endif;
				
			?>
		</div>
	</main><!-- .site-main -->
</div><!-- .content-area -->

<?php
get_footer();

Notice the template that I passed in as the 1st arg is template-parts/content, remember to create this file (`template-parts/content.phpo` and you may use the same content as template-parts/search.php

For the tag.php, paste the below codes.

<?php

/*
*
* The template for displaying Tag pages
*/
?>


<?php

get_header();
?>

	<div >
            <div class = "m-0 main">  
                <?php 
                    $tags = wp_get_post_tags($post->ID);
                    $tag = $tags[0]->name;
                    $option = 'tag='.$tag;
                    query_posts($option);
                
                    if( have_posts() ):
                        
                        while( have_posts() ): the_post(); 
                        
                                get_template_part( 'template-parts/content', get_post_format() );
                        
                        endwhile;
                        
                    endif;
                    
                ?>
		    </div>
	</div>

<?php
get_footer();

Notice the template that I used is still the same template-parts/content.php.

The End…

Hopefully by now you will be able to create your own theme for your WordPress site and be in total control of your own site look and feels.

In the next post, we will see how can we build our own WordPress Plugins.

Stay tuned!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*