Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 68 ยท Performance, Tools and Scaling

Performance Optimization

Find and fix slow WordPress pages: measure with Query Monitor, remove N+1 queries, trim autoloaded options, tune images and scripts, and improve Core Web Vitals.

A slow site loses visitors and rankings. The rule for performance work is simple and often ignored: measure first, then change one thing at a time. Guessing leads to plugins nobody needed and "optimizations" that save a millisecond. WordPress slowness usually comes from a short list of causes: too many or too slow database queries, a bloated wp_options table, heavy images, too many scripts, and no caching at all.

This lesson builds on Caching and WP-Cron and the query knowledge from WP_Query in Depth. It splits the work into server-side time (how long PHP and the database take to build the page) and browser-side time (how long the page takes to load, render and become interactive). The runnable examples are plain-PHP stand-ins over SQLite, and all WordPress code is read-only.

Measure before you tune

You cannot fix what you cannot see. Useful tools:

  • Query Monitor (a free plugin) shows every database query on a page with its duration, the PHP function that made it, and which plugin or theme was responsible. It also lists slow hooks, HTTP calls and PHP errors. It is the first tool to install on a development copy of a slow site.
  • SAVEQUERIES stores queries in $wpdb->queries for your own analysis (development only: it adds overhead). See Debugging WordPress.
  • Browser developer tools and Lighthouse show what the visitor experiences: the network waterfall, blocking scripts, image sizes and the Core Web Vitals.
  • Server timing (response time of the HTML document, called time to first byte or TTFB) separates "PHP is slow" from "the browser is slow".
flowchart TD
    A["Page feels slow"] --> B{"Is TTFB high?"}
    B -->|yes| C["Server side:<br/>queries, PHP, no page cache"]
    B -->|no| D["Browser side:<br/>images, scripts, CSS, fonts"]
    C --> E["Use Query Monitor and caching"]
    D --> F["Use Lighthouse and the network panel"]

Start by deciding whether the delay happens before the first byte or after it.

Slow queries and the N+1 problem

The most common server-side problem is too many queries, and the classic version is the N+1 query: one query fetches a list of N items, then your code runs one more query per item.

PHP
// Slow: runs one extra query for each post when meta is not primed.
$ids = get_posts( array(
    'post_type'              => 'book',
    'fields'                 => 'ids',
    'posts_per_page'         => 50,
    'update_post_meta_cache' => false,
) );

foreach ( $ids as $id ) {
    echo esc_html( get_post_meta( $id, 'author_name', true ) ); // a query each time
}

By default, WP_Query fetches the meta for all posts it returns in a single extra query (update_post_meta_cache is true) and the same for terms (update_post_term_cache). Those functions then read from the object cache. Problems appear when you turn those flags off but still read meta, or when you call lookups yourself in a loop (a user, a term, a custom table). The fixes:

  • Leave update_post_meta_cache and update_post_term_cache on if you will read meta or terms. Turn them off only when you truly need just the posts, for example with 'fields' => 'ids' for a count or an ID list.
  • Prime caches in bulk: update_meta_cache( 'post', $ids ), _prime_post_caches() and get_users( array( 'include' => $ids ) ) fetch many rows in one query.
  • Batch your own custom queries with WHERE id IN (...) instead of a query per row.
  • Add 'no_found_rows' => true to queries that do not paginate; it skips the extra COUNT query.

The stand-in below counts queries for the two strategies over SQLite.

PHP N+1 queries versus one batched query

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With 20 items the difference is 21 queries against 2. With 500 items on a shared database server, it is the difference between a fast page and a timeout.

Other query patterns to look for: posts_per_page => -1 on large sites (always set a limit), orderby => 'rand' (it sorts the whole table), searches with a leading wildcard LIKE '%term%', and heavy meta_query filters on unindexed meta_value columns, which were covered in Meta Queries and Taxonomy Queries. Cache the results of unavoidable heavy queries in a transient or the object cache.

Autoloaded options

The wp_options table holds settings, and rows with autoload set to a loading value are fetched in a single query on every request and kept in memory (the core alloptions cache). Old plugins that stored big arrays, logs, or cached HTML as autoloaded options make this payload huge, which slows every page, including cached-miss pages and the admin.

WordPress 6.6 changed how this flag is stored (values such as on, off, auto, with yes and no still accepted) and added a Site Health check that warns when the autoloaded data is large, around 800 KB. To inspect it, list the biggest autoloaded options with SQL or WP-CLI:

Terminal
wp db query "SELECT option_name, LENGTH(option_value) AS bytes FROM wp_options WHERE autoload IN ('yes','on','auto-on','auto') ORDER BY bytes DESC LIMIT 10"

When adding an option that is large or rarely used, pass false for the autoload argument: update_option( 'myplugin_log', $data, false ) or, better, keep logs in a custom table or a transient. Remove leftover options from plugins you deleted, after taking a backup. The Options API lesson explains the flag in detail.

The audit below mimics that diagnostic: it sums the autoloaded size, shows the biggest offenders and prints a warning above a threshold.

PHP Auditing autoloaded options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The two oldest rows (a dead slider cache and a crawl log) account for almost all the weight. That pattern, a forgotten plugin's data, is by far the most common cause.

Images

Images are usually the heaviest part of a page. WordPress already does a lot for you: it generates several sizes, adds srcset and sizes so the browser picks a suitable width, and since 5.5 adds loading="lazy" to images below the fold. (See Images, Thumbnails and Media.) You can improve it further:

  • Upload at a sensible size. A 6000-pixel photo for an 800-pixel column wastes time even if WordPress makes smaller copies.
  • Use modern formats such as WebP and AVIF. Core can create WebP (and, with server support, AVIF) sub-sizes, and image plugins can convert existing files.
  • Do not lazy-load the main image above the fold. Core avoids it for the first content image; for your own templates, add fetchpriority="high" to the LCP (largest) image and leave loading off it.
  • Give images width and height so the layout does not jump while they load (wp_get_attachment_image() does this for you).

Scripts and styles

Every plugin can add its own CSS and JavaScript to every page. Load only what a page needs, by adding conditions where you enqueue (see Enqueuing Styles and Scripts):

PHP
add_action( 'wp_enqueue_scripts', function (): void {
    if ( is_singular( 'event' ) ) {
        wp_enqueue_script(
            'myplugin-map',
            plugins_url( 'js/map.js', __FILE__ ),
            array(),
            '1.4.0',
            array( 'in_footer' => true, 'strategy' => 'defer' )
        );
    }
} );

Use defer so the script does not block rendering, load scripts in the footer, and dequeue assets from plugins that load them everywhere (for example contact form scripts on pages without a form). Minifying and combining files is less valuable than it was with HTTP/1.1: with HTTP/2 or HTTP/3 many small files are fine, and removing unused code helps more than merging.

Hosting, PHP and the CDN

  • Use a current PHP version with OPcache enabled. It caches compiled PHP and is usually a free, large win.
  • Put a page cache in front, as described in the previous lesson. A cached page can be served in a few milliseconds without PHP.
  • Use a CDN for static files (images, CSS, JavaScript) so they are served from a location near the visitor. Many CDNs can also cache whole pages for logged-out traffic.
  • Keep the database healthy: delete post revisions and spam you do not need, and limit revisions with define( 'WP_POST_REVISIONS', 10 ).
  • A persistent object cache (Redis or Memcached) cuts database load on dynamic, uncached pages.

Core Web Vitals

Google measures real-world experience with three metrics, and they connect directly to the advice above:

Metric Measures Typical WordPress fixes
LCP (Largest Contentful Paint) How fast the main content appears Page cache, fast TTFB, optimized hero image with fetchpriority="high", less render-blocking CSS
INP (Interaction to Next Paint) How quickly the page responds to input Fewer and lighter scripts, avoid long JavaScript tasks, remove heavy plugins
CLS (Cumulative Layout Shift) How much the layout jumps Image width and height, reserved space for ads and embeds, careful font loading

Improve what the real data shows is worst (use field data from a tool such as the Chrome UX Report or PageSpeed Insights), not what a lab score suggests. A final habit: after each change, measure again, and revert changes that did not help.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is an N+1 query problem?

    The pattern fetches a list with one query, then runs another query inside a loop for every item. The fix is to batch the lookups or prime the cache.
  2. 2. Which option on WP_Query avoids an unnecessary COUNT query when you do not paginate?

    no_found_rows skips the SQL_CALC_FOUND_ROWS or COUNT work used to compute total pages. posts_per_page => -1 loads every post, which is usually worse.
  3. 3. Why can large autoloaded options hurt every page?

    Autoloaded rows from wp_options are fetched on each request, so big values add database time and memory to every page, cached or not at the page level.
  4. 4. Which image should NOT get loading="lazy"?

    Lazy loading delays an image until it is near the viewport. The main above-the-fold image should load as early as possible, ideally with fetchpriority="high".

Summary

  • Measure first: Query Monitor for the server side, Lighthouse and field data for the browser side.
  • Remove N+1 patterns by batching and priming caches; keep the meta and term caches on when you read meta or terms, and avoid unbounded or random-ordered queries.
  • Keep autoloaded options small: pass false for big, rarely used values and clean up after removed plugins.
  • Serve right-sized modern images, load scripts conditionally with defer, and use OPcache, a page cache and a CDN.
  • Tie each change to a Core Web Vitals metric (LCP, INP, CLS) and verify it with a new measurement.

Next, automate the routine jobs from the command line: WP-CLI.