Getting started with templating in WordPress

What is a template and how does it work

WordPress comes with many powerful features right out of the box. One of the most regarded is the support of themes. A theme is a set of template files and functionality that is accessed by the WordPress core to render your website.

Public repository vs creating your own

Templates can be easily downloaded from the public repository. This is a convenient option if you are just getting started. Without the need to respect a design guide, you may simply browse the public repository until you find a theme that looks like a perfect choice for your website. This feature accounts for most of WordPress’s success among small businesses and sole traders.

The other way is to create your own theme or hire someone to do it for you. This is certainly more difficult than selecting a random theme, but tends to pay itself off on the long run.

Optimising a general all-purpose theme can become a nightmare especially if changing it is not an option. Once you have thousands of users expecting your site to look the way it does, your options are limited.

We are not advising one over the other. While you are small and want to do everything by yourself, it is a good idea to save time and money on using a general theme. Later however if speed, ranking and user experience suffers due to some limitations imposed by your theme, you may need to consider a fix.

In the rest of this article, we will be focusing on the anatomy of a theme.

File structure

WordPress has a built in routing engine. It means that every time you visit a WordPress website, it looks at the url and decides what files to load to compile the web page that is presented to you.

Pages generally share common headers, footers, scripts and style sheet files but load different content.

To tell exactly what template will be used for a specific page or post, you need to be familiar with the template hierarchy.

WordPress template hierarchy. If you are a developer, print it now and stick it on your wall. 🙂

If you need to make changes to an existing theme, simply locate the right right file, update it and voilá. Simple.

If however you decide to build your own template, it may take a little more effort. The recommended way is to use a non-distracting boilerplate. Our all time favourite is blankslate by tidythemes.

Page structure

In the early years of the internet, static websites were the standard. A static website means that you write some html, link your css and javascript files, copy the whole thing onto your web server and you’re good to go. The downside is obviously the relative lack of ability to edit (at least not in a web browser)

WordPress lets you edit the content of your website through your admin area. How is this possible?

The key to understand is the following: what can change, WordPress stores in a database while what is likely to be static is stored in files.

The static part of a page can also consist of multiple elements. For example a shared header and content layout and a footer specific to the given page.

The template file is located according to the template hierarchy while template parts are loaded using hooks.

Hooks

Hooks are a powerful yet simple way of interacting with the core functionality provided by WordPress. Worth mentioning at this point that WordPress is written in PHP and therefore using virtually any of its functionality through directly editing files requires a strong understanding of it.

Hooks take care of a specific piece of functionality.

The hook get_template_directory_uri() as an example will return the url that points to your local template directory while get_header() will… can you guess? Yes, it gets the header.

This article is designed to give you an oversight of what you need to know to build a theme. We won’t go deeper into hooks for now. If you want more knowledge, look no further than the official documentation.

Custom functions

In your template directory you will find (or need to create) a file named functions.php

This is where your theme’s logic is found or need to be placed. Every time you need to register a new widget or add template support for a new functionality, you’ll be working with this file.

There are times though when you need something very specific to your application. Let’s see through an example, how you can display the date 2 weeks from today in your pages.

In your functions.php:

function dateInTwoWeeks() {
    $today = new DateTime();
    $twoWeeksFromNow = $today->modify('+14 days');
    return $twoWeeksFromNow->format('d-m-Y');
}

// In any of your template files

<?php echo dateInTwoWeeks(); ?>

That’s it. You can use any custom functionality in your WordPress application.

Widgets

Widgets are dynamically placed elements that can be defined in your admin area and stored in the database. First you need to register your widget areas. Find out how in this article.

Once your widget areas are ready, you can edit them in the Appearance -> Widgets section of your site.

Templating engine

The last 2 point here are completely optional and require more advanced skills not only in PHP but concepts like OOP and MVC as well as managing packages.

We love templating engines. They make life easier and speed up the workflow at the same time. Check out Twig and Blade to have an idea. These can be used as part of robust mvc frameworks they have originally been developed for, but they are also available through composer as standalone packages.

composer require twig/twig

composer require philo/laravel-blade

To take full advantage of this approach, you need to have advanced skills and know how to install composer on your server, autoload your components or manage composer cache.

With this said, let’s see what is needed to use your favourite templating engine in WordPress.

To use philio/blade, simply define the blade template file to be loaded on your WordPress template file:

<?php require 'vendor/autoload.php'; // Autoloading the packages

use Philo\Blade\Blade; // Let's use Blade

$views = __DIR__ . '/views';
$cache = __DIR__ . '/cache';

$blade = new Blade($views, $cache);
echo $blade->view()->make('page')->render(); // Grab a template file and render it.

Now create a views directory within your theme and define your blade template files according to the documentation.

The benefit? You’ll end up with a much more readable code and clean template structure you have full control over.

Javascript frameworks

Do you happen to love working with React or Vue? Have you ever wondered how cool it would be to finally turn your back to jQuery? By no means we say jQuery isn’t a wonderful tool in its own right. It used to be the only solution over plain JavaScript. In recent years however, its fame has significantly faded. The reason is the entrance of the powerful JavaScript frameworks that make it painless and actually quite enjoyable to add advanced interactivity to web applications.

Our choice is Vuejs for WordPress projects.

You can simply install it through npm and load the single compiled file using the wp_enque_script() hook.

Once you are done with the development, make sure that you compile your Vuejs in production mode as it will significantly reduce the file size.

Static assets

Minifying css can be a pain sometimes. Search engines tend to react negatively to unminified assets. Find out more about what is minification.

Tools like webpack and Laravel mix are powerful and simple to combine and optimise your asset files.

Conclusion

Thank you for reading this article. It is not easy to build a WordPress theme that performs to the highest standards, looks beautiful on all devices and simple to edit. It is a nice challenge though and if you are looking to stand out, it is an effective way.

Please share your thoughts in the comments section.

10 causes why your WordPress site is slow

WordPress has many obvious benefits. We don’t blame you if you thought, getting your personal or business up and running with it will be as simple as it looks from a distance. What many people realise later on is their website is becoming increasingly more difficult to maintain, gets hacked, slows down and ranks low on search engines.

If this sounds familiar, we are here to help and tell you why this is happening. In the following, you can find out more about the most common reasons why your WordPress website can be sluggish.

1. Missing updates

WordPress has an incredible contributor community. The frequency of new stable releases is extraordinary considering the flexibility of the project. It is easy to forget to update your website especially if you are not confident in how to deal with the situation if the update fails. Having the latest version however is the safest bet to maintain speed and prevent hacking on the long run.

wordpress-updates
You should keep your site up to date. It is simple to do yet has a huge effect on your site performance.

Updates fall into 4 categories.

  • Core – is a catch all phrase for the logic that enables your website to run. Once an update is part of the new stable release, you can be 100% certain, it is for a very good reason. All updates are carefully reviewed and tested, so technically none of them should break your site.
    If a core update breaks your site, the issue is very likely to be found in the way your custom parts – such as theme and plugins – are built. It is an urgent matter and should be investigated asap. If your site falls behind on updates, it becomes more and more vulnerable to hacking.
  • Plugins – are well managed through the public repository within WordPress. Publishers have the option to release updates to their work, so once they are available, users like you get notified. Plugin updates aren’t always free from errors, but the general rule of thumb is: if a plugin doesn’t support the latest version of WordPress, you probably shouldn’t use it very long.
  • Themes – are interesting because you get notified of updates of themes you have installed but don’t use. Unless you are planning to change the entire look and feel of your website (and probably confuse the heck out of your users), it is a good idea to remove all unused themes. Once you have settled with the right one for you, you should always make sure that the theme is up to date.
The various categories of updates within WordPress

2. Too many plugins

The public plugin repository is awesome! It is a brilliant idea and extendability is probably responsible for the popularity of the framework. If you need a feature, you’ll be very likely to find a plugin that does something very similar (or exactly what you’re after if you are lucky). The sheer number of plugins indicate however that many of them simply do not meet the quality standards and ultimately slow your site down. Many plugins offer a stripped down version and let you purchase pro package. Unless the plugin is extraordinary in all respects, people often refrain from using paid pro plugins as there are almost always free alternatives.

Every plugin you install, adds some overhead when the page loads. The cumulative effect can easily be 12s loading time.
The general rules are: 

  • Install only what is crucial for your site to function.
  • Only use plugins that supports the latest version of wordpress
  • Remove all plugins you don’t need as soon as you deactivate them

3. Badly written untested or unsupported plugins

Plugins are often written by newbie developers or people who don’t bother respecting the quality guidelines provided by WordPress. This becomes a potential issue when the inefficiencies add up and cause you or your developer some precious time to investigate the source of the issue. Frequent updates, latest version support and star-rating are the most reliable measures to tell if a plugin is worth installing.

4. All-purpose theme

Themes that have plenty of controls and advertised as an all-in-one solution for all types of websites, usually don’t really work out for any site. The biggest issue is that settings need to be stored in the database, so at every page load they have to be accessed. This means that the server will need to perform a few more database queries before can pass the result to the browser. It is called server response time and it is fairly difficult to reduce once you have built your website using one of these themes. The ultimate solution is to have your theme being developed from scratch. Yes, it is more expensive and takes a bit more time too, but the benefits far outweigh the downsides.

5. Un-minified resources

Minification is a term used for removing all text from a code that does not have function other than helping to read the code such as line breaks, white space and comments. Once a piece of code is minified, it is very difficult to read and debug which is perfect for our purposes.

Our purpose is to keep the file size to the absolute minimum while maintaining the logic our code provides. Modern JavaScript frameworks like React or Vue are designed to work in development or production mode while tools like Webpack or Laravel Mix help combine and optimise assets brilliantly. You will not only have minified files but also one single file. In essence, your site really should not load more than one style sheet or JavaScript file to run.

When your css and JavaScript files are minified and combined, Google and other search engines will like your site much more and since it loads much faster, your users will appreciate too.

Minification and compiling your assets will have a strong positive effect on ranking and performance.

6. Not optimised imagery

If you use Photoshop, always use the save for web option when exporting your images. (CTRL+ALT+SHIFT+S (Windows), CMD+OPTION+SHIFT+S (Mac))

If not using Photoshop, you may want to locate an export option in your software that lets you determine what is the lowest possible resolution and quality that is still acceptable on your website. There is no need for super high-res photos for the following simple reasons:

  • They look exactly the same on a mobile device as if they were lower resolution
  • They load significantly slower
Save for web in Photoshop

Caching

Caching means that once your browser has downloaded certain assets, it is told how long it should keep it in its local storage (on your computer). The benefit is that stored assets load much faster that the ones downloaded from a server.

Please note that caching will not help much if your site takes ages to load initially. Users turned down at the first interaction will probably never come back. It works just like first impression of your new neighbour or colleague. If you don’t like John when you meet him, he’ll have a hard time to change it.

Ok, so let’s tell browsers to keep around files.

There is a file in your website public directory called .htaccess. This is where you can specify rules before your other files will be accessed on your server.

If you want to keep it simple, just add this to your .htaccess file.

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

Slow hosting

Not all hosting services are created equal. If your site sits on your own server, you have much more control over your server settings than if you are using shared hosting. In the latter case still you have a few options to make the most of your server resources.

We already mentioned briefly that your page speed will suffer if if your plugins make complicated database queries to dig out settings and alike. This type of issue requires a bit of housekeeping but definitely worth the effort.

Steps to get around it:

  1. Find out how long does your server take to respond when a user is trying to access your website. (Use your favourite tester tool or take our recommendation: Google Pagespeed Insights)
  2. Deactivate a plugin at a time and do a new test.
  3. If you find the cause, try to find an alternative. If it is a complicated piece of functionality, the best solution may be to get your very own plugin developed from scratch.

CDN/external resources

CDN stands for Content Delivery Network and this is exactly what it does. If all your static assets are stored on a lightning-fast server – and so load much quicker -, your site will perform better and much more likely to deal with busy times when hundreds or thousands of users accessing your site at the same time.

Our favourite solution is CloudFlare (https://www.cloudflare.com)

Hacking and malware

Last but not least WordPress receives lots of criticism about being vulnerable to hacking. There is definitely some truth to it unfortunately.

You can significantly improve your chances not being hacked by doing a few simple preventative steps:

  1. Hide your login screen (use this plugin to get it done in 5 minutes)
  2. Use an ssl certificate
  3. Generate keys (the official tool)
  4. Use strong passwords
  5. Change the default database prefix
Use the link in your wp-config.php to generate your unique application keys and replace the default values in this file with the result.

Thank you!

It looks like you are interested in making the most of your WordPress website. If this is the case, check out our article on the best practices by setting up a new WordPress website.

Thank you for reading this article. Please feel free to leave a comment and/or share it with your friends possibly facing similar challenges. Ultimately if you are looking for some expert help, we are more than happy to work with you speeding up your website. It has plenty of benefits. Have a nice day!