Everything You Need to Know about WordPress Object Caching

Everything You Need to Know about WordPress Object Caching

Speed is a contributing factor to your site's success, but it's also one of the most difficult areas to diagnose problems with. If you haven't already tested your site, Google's PageSpeed Insights Tool lets you know if your site could use improvements. Each suggestion will help you speed up your site, but WordPress developers can take advantage of an internal  API called WP Object Cache. This API reduces the number of queries sent to the database server by storing specific option data in a temporary table.

Caching Basics

Every time your visitors open your website, the content is retrieved from the backend database (most likely MySQL). The database processes queries and returns data to the web server. The web server then renders the results.

This process is fine for low-traffic sites, but imagine that you have a million pageviews a day. If each page has five queries during load time, you have five million queries sent to your database every day. The load on your database can be significant enough to degrade performance, which your visitors will experience. A slow website has a tremendous effect on your visitor retention. With just a 4 second delay, you've potentially already lost 25% of your visitors.

If you do a search, you'll find several types of caching. You can cache on the web server using its memory. You can use browser caching to force the user to keep data on their computer. Proxy servers can cache data for enterprise users. WordPress has its own API and type of caching called object caching. It is specific to queries made on stored options coded into themes and plugins.

Caching's main objective is to speed up your site, so any kind of caching is a benefit, but you might not always have the ability to control some kinds of caching. The WordPress Object Cache API is openly available to your developers, so it's a way to speed up your site without changing any server configurations.

More about WordPress Object Cache

While most caching options store content or pages, WP Object Cache uses the options stored in your theme or content. Each plugin or theme that you install on WordPress has its own options that it stores. WordPress has an Options API that stores each value. The most commonly used functions are add_option()  and get_option(). The Options API stores options in the database, so each time an option is retrieved a database query runs. It's not uncommon to have a dozen or more options in just one page of a WordPress site.

The Object Cache API stores specified objects in the database for one page load. One page load might seem like a short lifetime, but it's enough to increase the speed of your site. You cut the number of queries on your database in half (or more), because each time the user loads and reloads a page, only one query is needed for dozens of options.

WordPress has just a few Object Cache functions. The gist of the functions is that you add data to the cache with a corresponding key that is used to retrieve it again. You can optionally group data to use the same key across several options. A expiration time in seconds can be set on the cache. The default is 0, which means that it persists forever or until used but you can set a numerical value to delete cache for certain instances such as when the data might become obsolete.

WordPress also has a Transients API, which works similarly to the Options API, except Transients require an expiration time (in seconds). Transients’ data can also be stored in memory rather than the database. The Transients API should be used carefully, or it could cause technical errors on your site.

Redis with Object Cache

Redis (REmote DIctionary Server) is an open-source database store that uses in-memory stored data that sits as a "go-between messenger" for your MySQL database and the front-end of your WordPress application. It speeds up your site even more by providing an in-memory cache that WordPress can interact with instead of using MySQL resources. It's mainly used for data structures such as lists, maps, sets and sorted sets. If you have complex data storage, Redis is a performance upgrade option.

In terms of WordPress, Redis is popular for caching. It has other features, but caching is its main benefit when working with a WordPress site. You can use plugins to interact with Redis, or design a custom one to work with key features that you want to support on your site. The combination of storing data  in a way that is easy to retrieve, and keeping it in memory make Redis a great addition to performance optimizations  on your site.

Where to Go from Here?

The first step is to identify if your site has any speed issues. Google PageSpeed Insights is helpful, but you can also use GTmetrix as an alternative. You can find suggestions on what you can do to speed up your site, but if these suggestions don't offer enough of a performance boost, it's time to take other measures.

You can use plugins from the WordPress repository that implement Object Cache and Redis, but your options are limited. In some cases, it's better to build a custom plugin specific to your own site.

Whether you go for a custom plugin or a pre-made one from the WordPress repository, caching is an important part of performance optimization that you can leverage for a faster site. Take a look at your site’s speed to determine if it’s time to implement some of the available caching methods.

How to use Elasticsearch with WordPress in a Local Environment

Elasticsearch speeds up your WordPress site dramatically by replacing the default search “WP_Query” with the Elasticsearch system allowing visitors to search for More, and get Better results much Faster.

If you have not read our article "Why you should be using...." then [click here](https://www.MOZR.com "Why Elasticsearch") and see why you need Elasticsearch powering your site.

Before you dive headfirst into installing Elasticsearch on your server (check out our guide "How to install Elasticsearch"); you might want to first try it out in a local development environment.

There are lots of different ways to get a local WordPress install for development up and running. This guide will focus on setting up Elasticsearch with the most common ones; Vagrant and Docker.

The path via Vagrant

If your current WordPress development environment is using Vagrant, then there are a few things you need to do before powering your site with Elasticsearch.

Install ElasticSearch Service

The easiest way to get ElasticSearch running with Vagrant is to make a new Vagrant Box and run it as a separate VM. Luckily, all the heavy lifting is made easy using a VagrantFile created by Matthew McAchran on GitHub. All you need to do is clone the ["Elasticsearch Vagrant box" GitHub Repo](https://github.com/mmcachran/elasticsearch-vagrant) and let it do the work.  Open a new Terminal Window or Command Prompt and navigate to a folder for your new Vagrant Box (the location of this is up to you).

cd /usr/mozr/vagrant/boxes
git clone https://github.com/mmcachran/elasticsearch-vagrant

Now  go into the directory and tell Vagrant to spin up a new VM using the VagrantFile in there.

cd elasticsearch-vagrant
vagrant up

Running this takes a while as Vagrant needs to download a new image then set up a new machine.

IMPORTANT NOTE: This spins up a new VM with the IP Address of 10.0.0.11; if you already have a VM with this IP or you want to use another IP instead, edit the "Vagrantfile" in the `elasticsearch-vagrant` folder and change the line with `box_ip = '10.0.0.11'` to a suitable IP Address.

Once Vagrant has finished installing the new ElasticSearch Box, you should test it to make sure it is functioning correctly.  SSH into the server and send it a test command:

vagrant ssh
curl -X GET 'http://localhost:9200'

If ElasticSearch is installed you will get a response like this:

{

 "name" : "Burner",

 "cluster_name" : "elasticsearch",

 "cluster_uuid" : "kD2YBPEUTqCw_CM9inBFQQ",

 "version" : {

   "number" : "2.4.1",

   "build_hash" : "c67dc32e24162035d18d6fe1e952c4cbcbe79d16",

   "build_timestamp" : "2016-09-27T18:57:55Z",

   "build_snapshot" : false,

   "lucene_version" : "5.5.2"

 },

 "tagline" : "You Know, for Search"

}

The path via Docker

Getting Elasticsearch working in a local Docker environment is super easy. The Elasticsearch team have created a Docker image ready to use.

Setting up the Docker Image

Wherever you have Docker installed, just run the following command to retrieve the image:

docker pull docker.elastic.co/elasticsearch/elasticsearch:5.6.4

Once the image has finished downloading, you can bring up the new Docker container with the following command:

docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:5.6.4

If you get an error message about insufficient memory, then try setting the memory allocation for Elasticsearch to a lower amount. You can do this by modifying the command as follows:

docker run -p 9200:9200 -p 9300:9300 -e ES_JAVA_OPTS="-Xms512m -Xmx512m" -e "discovery.type=single-node" docker.elast
ic.co/elasticsearch/elasticsearch:5.6.4

This Docker image comes with [X-Pack](https://www.elastic.co/guide/en/x-pack/5.6/index.html) pre-installed and a trial license for 30 days. X-Pack adds security features to Elasticsearch, but this means you need to authenticate with the server. The default username is 'elastic' with a password of 'changeme'. For more information on the X-Pack Security feature check out [this page](https://www.elastic.co/guide/en/x-pack/5.6/security-getting-started.html).

Installing the ElasticPress Plugin

Now you need to install the [ElasticPress Plugin"](https://wordpress.org/plugins/elasticpress/ "ElasticPress on WordPress.org") made by the folks over at 10up. You can do this by downloading the plugin then installing it using your WordPress dashboard, or by using WP-CLI, the WordPress Command Line Interface system.

You can instruct WP-CLI to install the ElasticPress plugin directly from wordpress.org and follow the progress.

wp plugin install elasticpress --activate

Installing elasticpress (2.4)

Downloading install package from https://downloads.wordpress.org/plugin/elasticpress.zip...

Using cached file '/home/vagrant/.wp-cli/cache/plugin/elasticpress.zip'...

Unpacking the package...

Installing the plugin...

Plugin installed successfully.

Activating 'elasticpress'...

Plugin 'elasticpress' activated.

Success: Installed 1 of 1 plugins.

 

Connecting ElasticSearch with the ElasticPress Plugin

Now that you have the ElasticPress plugin installed on your WordPress site, and have ElasticSearch running; you need to do the final bit of configuration.

Firstly we need to tell your WordPress install where the ElasticSearch server is. You need to find the IP address of your Elasticsearch Docker Container.

You can do this by adding the following line to your wp-config file:

For Vagrant

‘EP_HOST’, ‘http://10.0.0.11:9200’

For Docker

‘EP_HOST’, ‘http://DOCKER_IP:9200/’

Alternatively, you can do it through the WordPress Dashboard.

Login to your WordPress Dashboard, then select "ElasticPress" from the navigation menu

Click the white "Set Up" Button

Enter the ElasticServer address (For Vagrant:  http://10.0.0.11:9200/ - For Docker: http://DOCKER_IP:9200/) into the box and click blue "Save Changes" button

Now all that is left is to sync the current WordPress database to Elasticsearch. Luckily the plugin can do all this for us automatically.

Just click the Sync Icon in the top right hand corner, and the plugin does the rest.

If you want to use the AutoSuggest feature of Elasticsearch, you must either give the search input fields a type equal to “search” or give them a CSS class of  “search-field” or “ep-autosuggest.”

That is it, Elasticsearch is now installed, synchronized with your WordPress install and powering your searches!