10+ WordPress Performance Optimization You Can Do Without Plugin

Website speed is one of the major criteria Google uses to rank your site. If you have a slow site it not only hurts your search engine ranking but is also bad for your users. A performance optimized site not only helps you get higher ranking but also helps you generate more revenue from your site.

The question is how can you increase your site’s load time. There are many good plugins which can optimize your site and help you get faster website load time.

But there are also smaller tweaks which you can do yourself without using a plugin which can help you optimize your site for faster page speed.

Following code snippets are used to do specific tasks that might require a large plugin. You can add these snippets into your theme’s functions.php file and get the speed boost without having to use a plugin.

These snippets can be added in two ways.

  1. Add them into your theme’s functions.php file
  2. Install Code Snippets plugin if you do not want to edit your theme’s file.

I normally prefer to just have them in my theme’s functions.php file. But if you do use the theme method then make sure you create a child theme and add them into your child theme’s functions.php so that they do not get overwritten if you update the parent them.

Gzip Compression

One of the first thing you should do after your site is ready and live is enable gzip compression.

GZIP Compression is method of reducing the size of your website’s files including HTML, JS files, CSS, etc

WordPress does not by default enables gzip compression. So, you will have to manually enable it in your website. Most Cache plugins have this feature but in case you do not want to use a plugin then you can enable GZip compression by adding following code into your sites. .htaccess file.

.htaccess file is found in the root folder of your website. This file is usually hidden by default so if you cannot find then enable “force hidden files to show”.

Also, there is a high chance of site breaking if you make mistake while editing this file so make sure you take proper backup of the .htaccess file before editing it.

Once you have taken backup, then edit the .htaccess file and paste following code in it.

Enable Gzip Compression on Apache Server

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

Enable GZip Compress on NginX Server.
If you are running on NGINX, simply add the following to your nginx.conf file.

gzip on;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
gzip_vary on;
gzip_types text/plain text/css text/javascript image/svg+xml image/x-icon application/javascript application/x-javascript;

After this save your file and check your site if its opening or not. If there is no issue then go ahead and check if the compression is working or not by running a scan through “https://gtmetrix.com/”

Leverage Browser Cache

When a user opens your site, the browsers sends a request to your server asking for HTML, CSS, JS and image files to load your site. The server then sends this files to the browser.

Depending on the size of these files the time taken to load your site can increase drastically which increases the load time and if it takes too long then the user can abandon your site completely.

Browser Cache is a technology with which the browser stores the web page resources temporarily in the user’s system and the next time the users visits the site the browser instead of asking server to send resources, loads it up from the cache which in turn increases your sites speed and load time.

Browser Cache helps a lot if you want to reduce your bandwidth expenses, usage and load time.

WordPress by default does not enable browser cache. So to leverage browser cache for your site, add following code into your site’s .htaccess file.

Make sure you take backup before editing the .htaccess file.

Add Expires Headers (Apache)

# TN - START EXPIRES CACHING #
ExpiresActive On
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/svg "access 1 year"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/xhtml-xml "access 1 month"
ExpiresByType application/javascript "access 1 month" 
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresDefault "access 1 month"
# TN - END EXPIRES CACHING #

Add Cache-Control Headers (Apache)

# TN - BEGIN Cache-Control Headers
<ifModule mod_headers.c>
<filesMatch "\.(ico|jpeg|jpg|png|gif|swf|pdf|svg)$">
Header set Cache-Control "public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "private"
</filesMatch>
<filesMatch "\.(x?html?|php)$">
Header set Cache-Control "private, must-revalidate"
</filesMatch>
</ifModule>
# TN - END Cache-Control Headers

Remove Query Strings

If you analyze your site on GTMetrix then you might have seen a recommendation to remove query string from static files.

WordPress by default adds a query string to all CSS and JS files used in your site. Having a query string in static file might make some CDNs to not cache these files.

Add this code to remove query strings from your static files.

function remove_cssjs_ver( $src ) {
if( strpos( $src, '?ver=' ) )
 $src = remove_query_arg( 'ver', $src );
return $src;
}
add_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 );
add_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 );

DNS Prefetch

DNS prefetching is an attempt to resolve domain names before a user tries to follow a link. This is done using the computer’s normal DNS resolution mechanism; no connection to Google is used.

Google

For an example, on a blog archive page – a user might click the first news whereas on the single post/page a user might click the home link or the logo to visit the homepage on your site. So, you can add DNS Prefetching for these links based on what you think your user might click next. You can use the following code snippet and paste it your theme’s functions.php to enable DNS Prefetching in single post .

if( ! function_exists( 'wphelp_dns_prefetch' ) ) :
 
    function wphelp_dns_prefetch(){
         
        if ( is_singular() ) { 
                  echo '<link rel="prefetch" href="' .esc_url( home_url() ) . '">';               
                   echo '<link rel="prerender" href="' .esc_url( home_url() ) . '">';             
        }
 
    }
 
endif;
 
add_action('wp_head', 'wphelp_dns_prefetch');

This snippet will enable DNS Prefetching on single post, so when a user is on single post or page or any custom post type and clicks on the link for homepage then the homepage will open without any delay.

Note: DNS Prefetching only works with HTTP2. So, if your server does not support HTTP2 then this will not work.

Disable XML-RPC

The WordPress XML-RPC is a specification that aims to standardize communications between different systems. It uses HTTP as the transport mechanism and XML as encoding mechanism which allows for various data to be transmitted

Are you using any desktop based application to write post for your blog ? If not then its best to disable XML-RPC on your site. XML-RPC could also be used to do DDOS attack on your site so its best to disable it if not in use.

add_filter('xmlrpc_enabled', '__return_false');

Disable or Reduce Post Revisions

WordPress by default Auto-Saves the posts drafts and all the changes you make into your posts/pages in the site’s database. This can quickly increase the size of your database if you make a lot of changes into your pages or post.

Ask yourself, how many times have you gone back to retrieve posts from old version? Probably , hardly once or never.

You can either disable Post revisions completely or limit it to smaller number.

To disable Post Revision add this code:

define('WP_POST_REVISIONS', false);

To limit Post Revisions to max 3 versions add this code:

define('WP_POST_REVISIONS', 3);

Disable WordPress Heartbeat

Introduced in WordPress 3.6 the WP HeartBeat API is method through which WordPress communicates with the web-browser and the server. This API helps in better user management, auto saving of posts, pages and to manage post revisions.

WP Heartbeat API works by calling the admin-ajax.php file and on server with low memory or shared hosting this can significantly slow down the website.

To disable WP HeartBeat API, add following code:

add_action( 'init', 'stop_heartbeat', 1 );
function stop_heartbeat() {
wp_deregister_script('heartbeat');
}

Disable ACF on Frontend

ACF or Advanced Custom Fields is a WordPress plugin to create custom Meta Boxes on your site. It is currently being used on more than 1+ million sites. Most sites uses ACF to show meta boxes in the Admin area of the site and rarely use it on the front-end.

Despite that, ACF loads, JS/CSS files on the front-end as well which can add more resources on the front-end of your site.

If you use ACF on your site, you can disable the JS/CSS files added by ACF from loading on front-end by adding following code:

// disable acf css on front-end
add_action( 'wp_enqueue_style', 'wphelp_deregister_styles', 100 );
 
function wphelp_deregister_styles() {
 if( ! is_admin() ) {
  wp_deregister_style( 'acf' );
  wp_deregister_style( 'acf-field-group' );
  wp_deregister_style( 'acf-global' );
  wp_deregister_style( 'acf-input' );
  wp_deregister_style( 'acf-datepicker' );
 }
}

Remove URL field from your Comment Form

WordPress by default links the Comment Users name to the URL they enter while posting the comment. One of the reasons you get spam comments is because spammer want to get a link from your site. They see that your site’s comment form has a URL field and they try to spam it.

One of the way you can reduce comment spam is by disabling the URL field. Don’t give them the one thing they are looking for.

Your genuine users would still comment without adding their website but the spammer won’t have that motivation without a field to enter their website’s URL.

To disable URL from Comment form add following code:

function wphelp_disable_comment_url($fields) { 
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','wphelp_disable_comment_url');

Disable WordPress Search

If you are not using WordPress Search functions then it’s better to disable it. This can help if you are running your site on a low spec server or just don’t want your user to search through your content.

To disable search from your site add following code to your theme’s functions.php file

function wphelp_filter_query( $query, $error = true ) {
if ( is_search() ) {
$query->is_search = false;
$query->query_vars[s] = false;
$query->query[s] = false;
// to error
if ( $error == true )
$query->is_404 = true;
}
}
add_action( 'parse_query', 'wphelp_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Protect Your Site from Malicious Requests

You can try various methods to secure your site. You can use a Security plugin, a firewall but attackers always finds a way. Attacker try combination of methods to penetrate your site. Most common among this is using malicious URL to inject code into your database.

Use this following code to disable all bad URL requests:

global $user_ID; if($user_ID) {
    if(!current_user_can('administrator')) {
        if (strlen($_SERVER['REQUEST_URI']) > 255 ||
            stripos($_SERVER['REQUEST_URI'], "eval(") ||
            stripos($_SERVER['REQUEST_URI'], "CONCAT") ||
            stripos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
            stripos($_SERVER['REQUEST_URI'], "base64")) {
                @header("HTTP/1.1 414 Request-URI Too Long");
                @header("Status: 414 Request-URI Too Long");
                @header("Connection: Close");
                @exit;
        }
    }
}

How to Add These Code Snippets ?

As mentioned above you can add these snippets into your theme’s functions.php file but if you are not comfortable editing the theme files then you can install the “Code Snippet” plugin and add all the code in it.

Code Snippets is an easy to use plugin which lets you add snippets into your file without having to edit any theme files.

  1. Install the plugin and Activate it
  2. Click on “Add New” under Snippets
  3. Give the snippets a handy name so you can remember it.
  4. Paste the code in the editor that opens and
  5. Click Save Changes and Publish

This way you can add the code snippets without having to edit any file and these code snippets will not be deleted even if you change the theme.

If you have a favorite WordPress snippet that you like to use please share it in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *