1. Code
  2. Coding Fundamentals
  3. Performance

Speed Up WordPress: Caching and Database Optimization

Scroll to top
Read Time: 8 min
This post is part of a series called Speeding Up WordPress.
Speed Up WordPress: Using CDNs, Compression, and Minification

One of the most popular talking points in the WordPress community is speeding up WordPress and optimizing web pages. I don't think there is a WordPress blog without an "X Tips to Speed Up WordPress" article. Don't get me wrong, it's a good thing. But we need better articles about this topic instead of dull plugin round-ups.

This may look like yet another "tips for speeding up WordPress" tutorial, but in this three-part series, we're going to go through every aspect of optimizing and speeding up your WordPress website.

Let's start with the most popular and probably the easiest thing: caching.

Caching in WordPress

I think it's safe to say that this is the most popular topic when it comes to speeding up WordPress. Granted, this is because of the popular and easy-to-use WordPress caching plugins, but it's also one of the fundamental techniques of reducing database load and speeding up WordPress websites.

We're going to get back to caching plugins, but let's look at the two types of caching: server-side caching and client-side caching.

Client-Side Caching

Client-side caching is the type of caching your visitors' browsers do. That means when visitors come to your website, their browsers will store data of certain parts of your pages. While browsers do cache some data automatically (like caching JavaScript and CSS files), we can do some fine-tuning with the help of .htaccess files.

By fine-tuning the .htaccess file, I mean adding the "Expires" header in it. You might have heard the term "leveraging browser caching" because it's commonly used in "website optimization" tutorials, and it's a high-priority criterion in the Google PageSpeed service.

Luckily, we don't have to come up with these headers ourselves—there's plenty of code ready to be "borrowed" on the web. I like the one in the HTML5 Boilerplate, where the headers are divided by categories of file types:

# ------------------------------------------------------------------------------
# | Expires headers                                                            |
# ------------------------------------------------------------------------------
# Serve resources with far-future expires headers.
# IMPORTANT: If you don't control versioning with filename-based cache
# busting, consider lowering the cache times to something like one week.
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"
  # CSS
    ExpiresByType text/css                              "access plus 1 year"
  # Data interchange
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/ld+json                   "access plus 0 seconds"
    ExpiresByType application/vnd.geo+json              "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"
  # Favicon (cannot be renamed!) and cursor images
    ExpiresByType image/x-icon                          "access plus 1 week"
  # HTML components (HTCs)
    ExpiresByType text/x-component                      "access plus 1 month"
  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"
  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"
  # Manifest files
    ExpiresByType application/manifest+json             "access plus 1 year"
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"
  # Media
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"
  # Web feeds
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"
  # Web fonts
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType application/         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"

Place these lines of code in your .htaccess file and you're good to go!

Server-Side Caching

When it comes to server-side caching in WordPress, we can talk about four major kinds of caching: page caching, database caching, object caching, and opcode (operation code) caching. Sourav Kundu explains this in his article at WP Explorer, but let's recap:

  1. Page Caching: In essence, WordPress outputs your pages by querying databases and loading the results. Page caching, however, stores each page as HTML files in the server's local storage (hard disk or RAM), and serves the HTML files corresponding to your pages each time your visitors visit your website.
  2. Database Caching: While databases are the "brains" of a WordPress website where all data are stored, it's not very effective when WordPress makes the same non-altering query over and over again on each page and for each visitor. Database caching saves and serves the results of these queries, and refreshes the results when an altering query is made.
  3. Object Caching: This is an internal API of WordPress that allows plugins to store data of expensive queries in the memory. It's a bit irrelevant for our series—maybe we'll go through this in a separate tutorial in the future.
  4. Opcode Caching: Just as you add flour, water, eggs, sugar and whatnot every time you bake a cake, the codes in your PHP files are instructions to "compile" and make your requests. Opcode caching is the kind of caching that stores the compiled code, speeding up the process considerably.

WordPress Plugins on Caching

Our main chapters are the aspects of speeding up WordPress, so it might be off‑topic to review plugins. Nevertheless, it's a good idea to talk about a couple of plugins in each chapter. As for caching, I know you already know the two most popular plugins:

  1. WP Super Cache: This is the most popular caching plugin for WordPress, with over 6 million downloads and a 4.2 star rating as I'm writing this article. Simply put, WP Super Cache works by generating static HTML files of your pages and refreshing them with an interval that you set (an hour by default). This works like magic out of the box even in shared hosts, but may not be enough for high-traffic websites.
  2. W3 Total Cache: Being the second most popular plugin with almost 4 million downloads and a 4.5 star rating, W3 Total Cache is the kind of plugin that's more suitable for high traffic websites running from a VPS or a better hosting environment. With its wide range of settings and support for high-performance caching options, it might be the best solution for you if you know what you're doing. If you're not familiar with the jargon in the settings, however, you might as well use it out of the box and don't change any options, or you may break your front-end.

Optimizing the Database in WordPress

Databases are the "brains" of your website: They store the valuable data that you show on your pages. Static HTML websites store their data inside the pages, but content management systems have to rely on databases (SQL, NoSQL, XML, JSON and such) to store our data. WordPress is no different—it uses MySQL to store the static and dynamic content along with your website information, WordPress settings, user details and so on.

Databases are a powerful standard to keep, serve and alter your data, but if you use them wrong and forget to maintain them, they can get fat and bloated. And like any other software, WordPress needs maintenance, too. WordPress doesn't build up too much bloat in the database, but that doesn't mean it won't slow down your website.

You need to keep an eye on your post revisions, trashes of posts, pages, comments, etc., and any other kind of "stale" data. And every now and then, you must check your "database overhead", which is often compared to hard disk defragmentation or changing the oil of your car.

It's possible to maintain all of these manually: You can empty your trash, disable the "revisions" feature, delete spam comments and optimize the database overhead by logging in to phpMyAdmin, but that's not an optimized technique for database optimization. Instead, you can use a WordPress plugin to do all the work.

There are more than a few plugins that allow you to optimize your database with one click or even automatically. The one I like the most is WP-Optimize: It automatically cleans up and optimizes your database without any hassle.

WP-Optimize lists its main features as follows:

  • Removal of stale post revisions
  • Removal of stale unapproved and spam comments
  • Removal of trashed comments
  • Removal of Akismet metadata from comments
  • Removal of other stale metadata from comments
  • Mobile device friendly, now you can optimize your site on the go
  • Removal of all trackbacks and pingbacks
  • Cleaning up auto draft posts
  • Removal of transient options
  • Clear out the post trash
  • Automatic cleanup of all the integrated options (also uses retention if enabled)
  • Ability to keep selected number of weeks data when cleaning up
  • Option to add or remove link on wp admin bar.
  • Enable/Disable weekly schedules of optimization
  • Apply native WordPress MySql optimize commands on your database tables without phpMyAdmin or any manual query.
  • Display Database table statistics. Shows how much space can be optimized and how much space has been cleared.
  • Enabled for Administrators only.

Be sure to check out other database optimization plugins, but don't be negligent about maintaining your database.

On to Part 2

In the next part of the series, we'll be looking at the aspects of compression and minification, and using CDNs to make your WordPress website faster.

What do you think about speeding up WordPress? Share your thoughts below in the comments section. And if you liked the article, don't forget to share it.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.