How to monitor and reduce WordPress memory usage by plugins

WordPress memory

One of the best things about WordPress is that it’s so easy to extend your site’s functionality with the many (mostly) free plugins available on the plugin repository. But loading your site with too many plugins can cause your site to consume too many resources on your server, slowing your site down. So how do you find out what resources your plugins are consuming to help you reduce WordPress memory usage and speed up your site?

Reduce WordPress memory usage by plugins

In a WordPress page request, the point at which plugins are loaded depends on how they’ve been coded. WordPress runs through a series of typical actions on every request. You can see these actions here, including the order in which they are run. A plugin developer decided where in this their plugin is needed, depending on the functionality the plugin offers, and ‘hooks’ into one of these actions, overiding or extending the default WordPress functionality with their custom code. More general information on the basics of plugin writing is available at the WordPress Codex.

So, as an example you’ve got a site that has 10 (or more!) plugins. These are firing at different times during a page request, hooking into different actions, all over the place. So how do you go about monitoring which plugins are most intensive?

As standard, there isn’t an easy way to monitor what WordPress memory usage is as it loads all of the plugins you’ve got installed on your site. But there are three plugins that in tandem, can really help you to find out what’s causing your site to slow down. Let’s look at them.

1) P3 (Plugin Performance Profiler)

Created by the in-house team at GoDaddy, the P3 (Plugin Performance Profiler) plugin allows you to run a scan over your site to determine what resources your plugins are using, and when, during a standard page request. This allows you to see the worst offenders and reduce WordPress memory usage by removing them or finding alternatives.

Once you’ve installed the plugin running a scan is easy and quick, even on a large site. Once the scan is complete you’ll see a comprehensive results report such as this;

P3 (Plugin Performance Profiler) Report
P3 (Plugin Performance Profiler) Report

The Runtime by Plugin report shows you a simple pie breakdown of which plugins are causing the most load on your site during a page request. Very useful, and a very quick way for you to identify and reduce WordPress memory usage by removing plugins that you don’t need.

Even more useful is the Detailed Timeline, which shows when the plugins are being loaded during the page request, so you can see if any particular one is causing a problem at a particular point.

Detailed Timeline of plugin load
Detailed Timeline of plugin load

Using the P3 (Plugin Performance Profiler) is a great start, but how do we get more information about what’s causing our site to slow down?

2) Memory Viewer

As the developer of the Memory Viewer plugin says;

Memory Viewer is a WordPress plugin that allows you to view WordPress’ memory utilization at several hooks during WordPress’ execution. It also shows a summary of MySQL Queries that have ran as well as CPU time.

Once installed, administrative users will see a new panel at the bottom of every page;

Memory Monitor output
Memory Monitor output

The report shows the memory usage at every major action hook, along with statistics on time and MySQL usage. You can also choose to show the queries that are happening at each hook, and output allows gives you an idea as to what code is responsible, which allows you to pinpoint exactly which ones are causing excessive load.

Generally a good indicator is when you see the ‘Current Memory Usage’ column leap up significantly from one action to the next. Any large jumps are worthy of investigation, as there could be plugins running that are the cause, or custom scripts in your theme that need optimisation. By removing or optimising these blockages, you can reduce WordPress memory usage significantly and then retest to see the effect of your changes on page load speed.

3) Debug Bar

Finally, the Debug Bar plugin offers similar functionality to Memory Monitor, but installs a panel into the WordPress admin bar. It is also extendable via other plugins to track and monitor other data such as the errors and warnings that PHP may record when you have the WordPress debug, WP_DEBUG, switched on.

Personally I prefere the ease and simplicity of Memory Monitor, but there’s no doubt that Debug Bar is extremely powerful.

Debug Bar output
Debug Bar output

So that’s three different, easy ways to monitor your WordPress site and find out which plugins and scripts you need to consider removing or tweaking to reduce WordPress memory usage and speed up your site.

I’d be really interested to hear what other WordPress developers use to monitor and optimise their sites.

Simple A/B testing in WordPress with Google Analytics site experiments

As we’re about to make some significant tweaks and changes to the main product pages on the Smart Insights site, I’ve looked at a lightweight way to do simple A/B testing in WordPress.

What is A/B testing?

You’ll probably be aware of the concept, I’m sure!

A/B testing, also called split testing or multivariate testing, involves your site randomly selecting one of several versions of a page to show to a site visitor. The aim is to find out which one is most successful at converting your visitors.

AB-Testing
What is A/B Testing?

Why do you need it?

Put simply, how do you know if the changes you made to a page are working better than the earlier version unless you can compare them side by side?

A/B testing allows you to make changes from a position of intelligence – knowing the impact of the changes you make allows you to learn what works and what doesn’t, and make sure that you repeat the successes and not the failures.

A/B testing in WordPress

After doing the usual Google searches, I discovered several A/B testing WordPress plugins, the best of which seemed to be MaxA/B. It’s a comprehensive plugin, and as a result pretty complicated.

The problem – MaxA/B seemed to me to duplicate a lot of the metrics and data capture that is really the job of an analytics tool and the fact is, mostly all of us already have a system installed on our sites that is specifically geared around telling us how our site performs – Google Analytics.

It just didn’t seem to make much sense to install something else that duplicates something I already have – so I wanted to see if there was a simpler method to allow us to use Google Analytics and without installing a plugin. I discovered that there is – and it’s provided directly within Google Analytics.

Introducing Google Site Experiments

I use Google Analytics a lot, but this particular feature has completely passed me by. Apparently it used to be a separate system called Google Content Experiments but has been merged into Google Analytics back in August 2012.

Content Experiments is a somewhat different approach from either standard A/B or multivariate testing. Content Experiments is more A/B/N. You’re not testing just two versions of a page as in A/B testing, and you’re not testing various combinations of components on a single page as in multivariate testing. Instead, you are testing up to five full versions of a single page, each delivered to visitors from a separate URL.

More at the

Great – perfect for what we wanted to do, and easy enough to make it work with WordPress on the surface. It recognises that a user is on the page that you’re wanted to experiment with, and then randomly sends them off to one of the other pages you’ve got in the experiment. As a result we can set each version of the page up as a separate page within WordPress, and add each URL to the experiment within Google Analytics.

When you set up your experiment (full instructions ) you get some javascript code that you have to add to the <head> tag of the original page of your experiment;

Create a new experiment Google Analytics
Creating a new experiment in Google Analytics

The problem is that the <head> section of every page in WordPress is served from a single PHP file – header.php. Adding the Google experiments javascript code to this means it will fire on every page, and break your site as a result. So how do we use experiments with WordPress pages? There’s an easy solution.

Outputting the experiments code on your original page only

Firstly, log in to your WordPress site as an administrator and browse to the edit screen for the original page. Once there, look in your browser’s URL bar to get the page ID from the URL.

Getting the WordPress page ID
Getting the WordPress page ID

Now fire up your favourite code editor and open the header.php file in your active theme directory. Below the first <head> line add the following code, substituting your page ID instead of ***PAGEID***, and the experiment javascript code provided by Google Analytics in place of ***GOOGLECODE***;


<?php if (is_page(***PAGE ID***) ):?>

***GOOGLECODE***

<?php endif; ?>

Simple as that! Using the is_page function allows us to surround the output of our experiment code in a conditional statement – if the current page ID matches the ID of your original experiment page, the javascript will fire and the Google experiment will work.

Once installed on your site, Google will automatically randomise which of your test pages your users see and start to measure the success of each, and depending on the length and configuration of the experiment will eventually declare a ‘winner’.

I’m keen to hear what other WordPress developers are using for doing simple A/B testing in WordPress – are you using a plugin such as MaxA/B or have you had any experience of Google content experiments?

Disable WordPress notifications email for users and admins

Stop emailI’ve just had two separate issues in two days which needed me to try to disable WordPress notifications email. WordPress sends a lot of automated email, and it’s not so easy to see how to change or suppress it.

So I thought I’d share the solutions I found in case it saves anyone else time, or indeed if I forget how I managed it the next time I come across the problem.

1) Disable the automatic welcome email sent to users

WordPress always sends users an automated welcome email, which has their username and password, in plain text. This is bad – you really shouldn’t be receiving login details in plain text emails. The reason it does this is that on most WordPress sites, the user doesn’t get the chance to put in their own password, it’s generally created by WordPress and then – you guessed it – emailed to them.

I’ll put to one side that it really shouldn’t do this on this occasion and get to the point. On Smart Insights we allow our users to create their own password on sign-up using the s2member plugin that forms the backbone of our membership (more on that here). We also use a marketing automation platform called Office Auto Pilot (which is fantastic and highly recommended) which handles the bulk of our email.

Our users were getting confused by receiving two emails when they signed up – the (poor, text only) one from WordPress containing their username and password which they already knew, and then a minute later another (proper, formatted HTML) welcome from Office Auto Pilot.

So, I found out how to switch the WordPress notification off.

The function that handles new user notification is called, surprisingly, wp_new_user_notification. And upon inspection, this function is pluggable, which means you can override it entirely via a plugin. Note – a plugin – not your theme. This code will not work in your functions.php file – it must be run from a plugin. The codex shows the following code to override the email;


// Redefine user notification function
if ( !function_exists('wp_new_user_notification') ) {

function wp_new_user_notification( $user_id, $plaintext_pass = '' ) {

$user = new WP_User( $user_id );

$user_login = stripslashes( $user->user_login );
 $user_email = stripslashes( $user->user_email );

$message = sprintf( __('New user registration on %s:'), get_option('blogname') ) . "\r\n\r\n";
 $message .= sprintf( __('Username: %s'), $user_login ) . "\r\n\r\n";
 $message .= sprintf( __('E-mail: %s'), $user_email ) . "\r\n";

@wp_mail(
 get_option('admin_email'),
 sprintf(__('[%s] New User Registration'), get_option('blogname') ),
 $message
 );

if ( empty( $plaintext_pass ) )
 return;

$message = __('Hi there,') . "\r\n\r\n";
 $message .= sprintf( __("Welcome to %s! Here's how to log in:"), get_option('blogname')) . "\r\n\r\n";
 $message .= wp_login_url() . "\r\n";
 $message .= sprintf( __('Username: %s'), $user_login ) . "\r\n";
 $message .= sprintf( __('Password: %s'), $plaintext_pass ) . "\r\n\r\n";
 $message .= sprintf( __('If you have any problems, please contact me at %s.'), get_option('admin_email') ) . "\r\n\r\n";
 $message .= __('Adios!');

wp_mail(
 $user_email,
 sprintf( __('[%s] Your username and password'), get_option('blogname') ),
 $message
 );
 }
}

Using that would allow you to tweak the welcome message to something a bit more detailed and ‘on-brand’ than the default one, which is useful info in itself. In my case though, all I wanted to do is stop it from sending the email at all. So, this did it for me;


if ( !function_exists('wp_new_user_notification') ) {

function wp_new_user_notification( ) {}

}

2) Disable the ‘user x has changed their password’ emails to the admin account

We use Help Scout for handling all of our user support, it’s simple and cheap (unlike Zendesk which from experience is neither of those) and does the job perfectly.  All emails sent by WordPress to the admin account are forwarded to Help Scout which handles them and assigns them out to support representatives. We use some of the notifications – comments and pingbacks, but we get lots of the ‘user x has changed their password’ emails, and we have to delete each support case generated by Help Scout manually. It’s annoying.

Another pluggable function to the rescue – wp_password_change_notification, which we can suppress be adding the following to a plugin – you can add this to the same plugin file you created for 1) if you like – it’ll work fine;

if ( !function_exists( 'wp_password_change_notification' ) ) {
    function wp_password_change_notification() {}
}

What about other automated emails?

Chances are there’s a pluggable function that allows you to suppress it – here’s a few more;

  • wp_notify_moderator – notifies the moderator of the blog about a new comment that is awaiting approval.
  • wp_notify_postauthor – responsible for sending comment notification emails to the post author when a reader leaves a comment

Take a look at the full list of pluggable functions at the Codex.

Cleaning and optimizing a WordPress database

When you’re running a high traffic WordPress site with a high posting volume it won’t take too long for your site database to contain a lot of clutter that can slow your site down. So how do you go about optimizing a WordPress database to speed your site up again?

Managing Post Revisions

Whenever you save a new version of a post, WordPress keeps the old version in the database as a Post Revision. Pretty much like Time Machine on a mac, this allows you to go back in time and retrieve your old post content if you accidentally overwrite it. You can use this feature underneath the main editor area when editing a WordPress post.

WordPress Revisions
WordPress Revisions

Great idea, right? Problem is, the default setting is overkill – there’s really no need to store 25 earlier versions, and when you’re running a large WordPress site like Smart Insights which has a new post at least every day, it quickly swells your database with unnecessary and unused information.

You can tell WordPress to limit the amount of post revisions it stores by adding an extra setting to the wp-config.php file:

define( 'WP_POST_REVISIONS', 3);

Adding this will restrict WordPress to storing three revisions for each post from that point forward.

But what about the revisions that are already in your database?

Ordinarily, the advice is to run mySQL queries directly on the WordPress database to clear the revisions out – but that’s not great for people who either don’t have direct database access or don’t really want to risk breaking their WordPress site by running direct database queries on it.

Last month I was introduced to a plugin – WP-Optimize – that handles this problem for you, and clears up other database clutter such as spam and unapproved comments, and even runs mySQL table optimisation routines too. Here’s the full list of what it does:

  • Removes WordPress post revisions
  • Removes WordPress auto draft posts
  • Removes all the comments in the spam queue
  • Removes all the un-approved comments
  • Applies mySQL optimize commands on your database tables without phpMyAdmin.
  • Displays Database table statistics. Shows how much space can be optimized and how much space has been cleared.

Having used this plugin for a month it’s now one of my ‘must install’ plugins when I create a new site, and a key part of my WordPress maintenance routine.

I’d love to know what tools other people use for optimizing a WordPress database – let me know in the comments.