Skip to content
πŸ“… Book a call
Blog

12 WordPress Speed Optimisation Code Snippets (No Plugins)

By Rajan Gupta

β€’ ⏱ 7 min read

No plugins. No fluff. Just the PHP, functions.php and .htaccess code I drop into every client site when agencies in the UK, Australia, USA and Canada need a fast WordPress build. Copy, paste, done.

I’ve optimised over 150 WordPress sites for agencies across the UK, Australia, USA, Canada, and Singapore. Every site gets the same baseline. Here it is.

1. Remove WordPress core bloat

A default WordPress install loads emoji scripts, oEmbed discovery, REST API headers, Windows Live Writer links and more β€” none of which your site needs. This removes all of it in one go.

Add to functions.php:

function rg_remove_bloat() {
    // Remove emoji scripts (~15KB + 1 HTTP request)
    remove_action( 'wp_head',            'print_emoji_detection_script', 7 );
    remove_action( 'admin_print_scripts','print_emoji_detection_script' );
    remove_action( 'wp_print_styles',    'print_emoji_styles' );
    remove_action( 'admin_print_styles', 'print_emoji_styles' );
    remove_filter( 'the_content_feed',   'wp_staticize_emoji' );
    remove_filter( 'comment_text_rss',   'wp_staticize_emoji' );
    remove_filter( 'wp_mail',            'wp_staticize_emoji_for_email' );

    // Remove oEmbed discovery links
    remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
    remove_action( 'wp_head', 'wp_oembed_add_host_js' );

    // Remove REST API link from head
    remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );

    // Remove shortlink
    remove_action( 'wp_head', 'wp_shortlink_wp_head', 10 );

    // Remove Windows Live Writer manifest
    remove_action( 'wp_head', 'wlwmanifest_link' );

    // Remove RSD link
    remove_action( 'wp_head', 'rsd_link' );

    // Remove WordPress version from head
    remove_action( 'wp_head', 'wp_generator' );
}
add_action( 'init', 'rg_remove_bloat' );

// Disable XML-RPC (common attack vector)
add_filter( 'xmlrpc_enabled', '__return_false' );

Impact: Removes 3–5 HTTP requests and up to 20KB per page load.

2. Remove query strings from static assets

WordPress appends ?ver=6.5 to CSS and JS files. This prevents proxy servers and some CDNs from caching those files. Remove them:

function rg_remove_query_strings( $src ) {
    if ( strpos( $src, '?ver=' ) ) {
        $src = remove_query_arg( 'ver', $src );
    }
    return $src;
}
add_filter( 'script_loader_src', 'rg_remove_query_strings', 15, 1 );
add_filter( 'style_loader_src',  'rg_remove_query_strings', 15, 1 );

3. Defer non-critical JavaScript

Render-blocking scripts are one of the most common causes of poor LCP scores. This adds defer to all scripts except jQuery (which breaks when deferred):


function rg_defer_scripts( $tag, $handle, $src ) {
    // Never defer these β€” breaks things
    $no_defer = [ 'jquery', 'jquery-core', 'jquery-migrate' ];

    if ( in_array( $handle, $no_defer ) || is_admin() ) {
        return $tag;
    }

    if ( strpos( $tag, 'defer' ) === false ) {
        $tag = str_replace( ' src=', ' defer src=', $tag );
    }

    return $tag;
}
add_filter( 'script_loader_tag', 'rg_defer_scripts', 10, 3 );

Important: Test after adding. Some sliders or form plugins break when deferred β€” add their handles to $no_defer if needed.

4. Preload fonts and critical assets

Tell the browser to fetch your fonts and hero image immediately β€” before the HTML parser even reaches them. This directly improves LCP:

function rg_preload_assets() {
    // Preload primary web font β€” update path to your font
    echo '' . PHP_EOL;

    // Preload hero image on homepage only β€” update path
    if ( is_front_page() ) {
        echo '' . PHP_EOL;
    }
}
add_action( 'wp_head', 'rg_preload_assets', 1 );

5. DNS prefetch and preconnect for external resources

If your site loads from Google Fonts, a CDN, or analytics, the browser does a DNS lookup first. Hinting it early cuts 100–300ms off perceived load time:

function rg_resource_hints() {
    $hints = [
        'preconnect'   => [
            'https://fonts.googleapis.com',
            'https://fonts.gstatic.com',
        ],
        'dns-prefetch' => [
            '//www.google-analytics.com',
            '//www.googletagmanager.com',
        ],
    ];

    foreach ( $hints as $rel => $urls ) {
        foreach ( $urls as $url ) {
            $crossorigin = ( $rel === 'preconnect' ) ? ' crossorigin' : '';
            echo '' . PHP_EOL;
        }
    }
}
add_action( 'wp_head', 'rg_resource_hints', 2 );

6. Force native lazy loading on all images and iframes

WordPress 5.5+ adds loading="lazy" to most images β€” but misses images added via ACF, custom fields, or theme templates. This catches everything:

7. Load WooCommerce scripts only on shop pages

WooCommerce loads its CSS and JS on every page by default β€” homepage, blog, contact, everything. For any WooCommerce store serving customers in Australia or the UK, this is a silent performance killer:

function rg_dequeue_woo_scripts() {
    if ( function_exists( 'is_woocommerce' ) ) {
        if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() && ! is_account_page() ) {
            wp_dequeue_style( 'woocommerce-general' );
            wp_dequeue_style( 'woocommerce-layout' );
            wp_dequeue_style( 'woocommerce-smallscreen' );
            wp_dequeue_style( 'woocommerce_frontend_styles' );
            wp_dequeue_script( 'wc-cart-fragments' );
            wp_dequeue_script( 'woocommerce' );
            wp_dequeue_script( 'wc-add-to-cart' );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'rg_dequeue_woo_scripts', 99 );

Real impact: On a WooCommerce store I optimised for a Sydney retailer, this single change removed 4 render-blocking requests and cut homepage load time by 800ms.

8. Throttle the WordPress Heartbeat API

WordPress pings your server every 15 seconds via the Heartbeat API for autosave and notifications. On shared hosting β€” common with small businesses in the UK and Australia β€” this creates constant unnecessary server load:

function rg_heartbeat_control( $settings ) {
    if ( is_admin() ) {
        // Slow it down to every 60 seconds in admin (default is 15)
        $settings['interval'] = 60;
    } else {
        // Disable entirely on frontend β€” nothing needs it there
        wp_deregister_script( 'heartbeat' );
    }
    return $settings;
}
add_filter( 'heartbeat_settings', 'rg_heartbeat_control' );

9. Limit post revisions and autosave interval

WordPress stores unlimited revisions by default. On a busy site this bloats the database significantly, slowing queries over time.

Add to wp-config.php (before the “That’s all, stop editing!” line):

// Keep only last 5 revisions per post
define( 'WP_POST_REVISIONS', 5 );

// Autosave every 120 seconds instead of 60
define( 'AUTOSAVE_INTERVAL', 120 );

// Increase memory limit if on shared hosting
define( 'WP_MEMORY_LIMIT', '256M' );

10. Browser caching via .htaccess

Tell browsers to cache static assets locally so returning visitors don’t re-download your CSS, JS, and images on every visit:

# Browser caching β€” add to .htaccess

    ExpiresActive On
    ExpiresByType image/jpeg                 "access plus 1 year"
    ExpiresByType image/png                  "access plus 1 year"
    ExpiresByType image/webp                 "access plus 1 year"
    ExpiresByType image/svg+xml              "access plus 1 year"
    ExpiresByType image/x-icon               "access plus 1 year"
    ExpiresByType text/css                   "access plus 1 month"
    ExpiresByType application/javascript     "access plus 1 month"
    ExpiresByType font/woff2                 "access plus 1 year"
    ExpiresByType font/woff                  "access plus 1 year"
    ExpiresByType text/html                  "access plus 1 hour"

11. Enable Gzip compression via .htaccess

Compress text-based assets before they leave your server. Gzip reduces HTML, CSS and JS by 60–80%. Supported by most hosting providers in the UK, Australia and USA:

# Gzip compression β€” add to .htaccess

    AddOutputFilterByType DEFLATE text/html text/plain text/xml
    AddOutputFilterByType DEFLATE text/css text/javascript
    AddOutputFilterByType DEFLATE application/javascript application/x-javascript
    AddOutputFilterByType DEFLATE application/json application/xml
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE font/woff font/woff2

12. Security and performance headers in one block

These are the exact headers I set on every client site β€” whether that’s a UK agency site, an Australian ecommerce store, or a US SaaS landing page:

# Security + performance headers β€” add to .htaccess

    Header set X-Content-Type-Options    "nosniff"
    Header set X-Frame-Options           "SAMEORIGIN"
    Header set X-XSS-Protection          "1; mode=block"
    Header set Referrer-Policy           "strict-origin-when-cross-origin"
    Header set Permissions-Policy        "geolocation=(), microphone=(), camera=()"
    Header set Cache-Control             "public, must-revalidate"

    # HSTS β€” uncomment only after SSL is confirmed working
    # Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"

    # Remove server signature
    Header unset Server
    Header unset X-Powered-By

Leave the HSTS line commented until you’re certain SSL is working. Getting it wrong locks users out for up to a year.

Quick reference

#SnippetFileTypical impact
1Remove core bloatfunctions.phpβˆ’3–5 HTTP requests
2Remove query stringsfunctions.phpBetter CDN caching
3Defer JavaScriptfunctions.php+5–15 LCP score points
4Preload fonts & hero imagefunctions.phpβˆ’200–400ms LCP
5DNS prefetch / preconnectfunctions.phpβˆ’100–300ms TTFB
6Force lazy loadingfunctions.phpβˆ’30–60% initial payload
7WooCommerce scripts on-demandfunctions.phpβˆ’800ms on non-shop pages
8Throttle Heartbeat APIfunctions.phpReduced server load
9Limit post revisionswp-config.phpSmaller, faster database
10Browser cache headers.htaccessInstant repeat visits
11Gzip compression.htaccessβˆ’60–80% transfer size
12Security + perf headers.htaccessCore Web Vitals + security

How I use these on agency projects

I maintain a private rg-performance.php mu-plugin that contains snippets 1–9, and an .htaccess base template with snippets 10–12. Every new project starts with both files. By the time a client’s site launches, the technical baseline is already solid.

When I work with Australian agencies as a white-label developer, this baseline is a genuine competitive advantage β€” their clients get 90+ PageSpeed scores as standard, not as a paid extra. Same for UK agencies, Canadian shops, and Singapore teams.

If you’re an agency owner looking for a WordPress developer who delivers this level of technical detail as a baseline β€” not an upsell β€” get in touch.

🎁 Free download

Get the free WordPress Security Checklist 2026

25-point checklist PDF β€” malware detection, hardening guide, login security. Used by 500+ WordPress site owners.

  • βœ“ 25-point security checklist PDF
  • βœ“ WordPress malware scan guide
  • βœ“ Hardening checklist for any WordPress site

No spam. Unsubscribe any time.

Need help with your WordPress site?

I'm a freelance WordPress developer who fixes exactly this kind of problem.

150+ projects. Clients in UK, US, UAE & Ireland. Fast turnaround.

Rajan Gupta

Rajan Gupta

Freelance WordPress Developer

Rajan Gupta is a passionate web developer and digital creator who loves sharing insights on WordPress, modern web design, and performance optimization. When not coding, they enjoy exploring the latest tech trends and helping others build stunning, high-performing websites.

Related Articles