Increase WordPress Speed just by adding some functions to functions.php. You can easily speed up your WordPress Theme by adding some custom functions. We are working on a speed optimized Theme and we wanted to share some of our code snippets. We used GTmetrix, Google Pagespeed Insights and Pingdom to analyze and speed up our theme.

Along the way we found that there are some simple tricks to speed up your WordPress Theme and fine tune it by adding some code to the functions.php, those snippets are custom for our Theme it might not work or fit the needs of yours.

Use at own risk and modify it to fit your needs, you do not have to use all of the code. You can start by adding them piece by piece and check if they do what they supposed to do. Hopefully this code can be useful for you and can benefit from some of the snippets.

Those snippets are for fine tuning and can improve page speed significant, however all little bits together makes a big difference.

You can start optimizing with a silly thing by adding php flush right after the head tag in your HTML. This will make the client browser start rendering the web page while your server still builds the output, it is about nanoseconds but what the heck all small things help.

Add PHP Flush after the head in your Theme

<?php flush(); ?>


Remove wp ‘?’ version param from any enqueued scripts

Remove the ‘?’ version parameter from WordPress enqueued scripts, this will make it cacheable, as scripts with a ‘?’ in it can not be cached.

/* ==========================================================================
*  Remove wp '?' version param from any enqueued scripts so it can be cached.
* ========================================================================== */
function cloudzola_remove_ver_css_js( $src ) {
if ( strpos( $src, 'ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
add_filter( 'style_loader_src', 'cloudzola_remove_ver_css_js', 9999 );
add_filter( 'script_loader_src', 'cloudzola_remove_ver_css_js', 9999 );

Remove Query Strings From Static Resources

Remove the ‘?’ version parameter from WordPress scripts, this will not make your website faster but might improve Page speed scores

/* ==========================================================================
*  Remove Query Strings From Static Resources.
* ========================================================================== */
function _remove_script_version( $src ){
$parts = explode( '?', $src );
return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );

Remove Query Strings From Static Resources except google fonts

This will not make your website faster but might improve Page speed scores. I found out that sometimes removing query strings breaks the site if you use Google fonts.

/* ==========================================================================
*  Remove Query Strings From Static Resources except google fonts.
* ========================================================================== */
/** function _remove_script_version( $src ){
if (strpos($src, 'googleapis') === false) {
$parts = explode( '?', $src );
return $parts[0];
} else {
return $src;
}
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 ); */

Load jQuery from Google API CDN

Load jQuery from Google API CDN, according to YSlow you should use a CDN and cookie free javascript. As most users have the Google hosted jQuery cached it will be served from the visitors cache and improve Page Speed. We use version 3.2.1 in this example, you can adjust it to the latest version.

/* ==========================================================================
*  Load jQuery from Google API CDN Version 3.2.1
* ========================================================================== */
function cloudzola_google_jquery() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_enqueue_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', array(), true, true );
}
}
add_action('init', 'cloudzola_google_jquery');

Load jquery in footer

This is not recommended if your website needs jQuery to be loaded in the header due to dependencies of Plugins or theme specific reasons. In most cases you can load it in the footer without problems.

/* ==========================================================================
*  Load jquery in footer 
* ========================================================================== */
function superfast_enqueue_scripts() {
wp_scripts()->add_data( 'jquery', 'group', 1 );
wp_scripts()->add_data( 'jquery-core', 'group', 1 );
wp_scripts()->add_data( 'jquery-migrate', 'group', 1 );
}
add_action( 'wp_enqueue_scripts', 'superfast_enqueue_scripts' );

Defer all javascript

By deferring all javascript you eliminate page rendering blocking resources, be sure to inline small javascript as this is a request less for every inlined script. Defer parsing JavaScript to reduce blocking of page rendering.

/* ==========================================================================
*  Defer javascript - You can replace defer with async
* ========================================================================== */
function cloudzola_js_defer_attr($tag){
# Add async to all remaining scripts
return str_replace( ' src', ' defer="defer" src', $tag );
}
add_filter( 'script_loader_tag', 'cloudzola_js_defer_attr', 10 );

Remove wp-embed.min.js

Since WordPress version 4.2 this was introduced and added extra lines of CSS and JavaScript code in the head & loading additional javascripts. This was added for extended support of emoji, removing the actions still let normal emoji works.

/* ==========================================================================
*  Disable this emoji support (added since WordPress 4.2) 
*  to prevent extra lines of CSS and JavaScript code in the head & loading additional javascripts.
*  This was added for extended support of emoji, removing the actions still let normal emoji works.
*  Remove if you need emoji support!
* ========================================================================== */
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );

Remove wp-embed.min.js and all other embedded scripts

Since WordPress Version 4.4 more scripts and styles where added automatically if you do not use the functionality you can disabling them by using this function. Most websites don’t use it and it is overhead. You can use in combination withe the code snippet above removing wp-embed.min.js, it makes no difference.

/* ==========================================================================
*  Remove wp-embed.min.js  and all other embedded scripts 
*  If you use Woocommerce or other dependencies remove this function!
*  This was added by WordPress since Version 4.4 & loads wp-embed.min.js in the header.
*  This disables all WordPress default embed functions!
* ========================================================================== */
add_action( 'init', function() {
                       
// Remove the REST API endpoint.
remove_action('rest_api_init', 'wp_oembed_register_route');
                       
// Turn off oEmbed auto discovery.
// Don't filter oEmbed results.
remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);
                       
// Remove oEmbed discovery links.
remove_action('wp_head', 'wp_oembed_add_discovery_links');
                       
// Remove oEmbed-specific JavaScript from the front-end and back-end.
remove_action('wp_head', 'wp_oembed_add_host_js');
}, PHP_INT_MAX - 1 );

Remove the admin bar and hide your WordPress Version

Some extra security and fancy thing to do is removing the admin bar for non admins, good for member sites or websites with subscribers and hiding the wordpress version in the head for improved security to prevent bots detecting you are using WordPress. Nothing to do with web page speed optimization, you do can benefit from some security.

/* ==========================================================================
*  Hide admin bar except for admins
* ========================================================================== */
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
show_admin_bar(false);
}
}
/* ==========================================================================
*  Remove WordPress Version from header and RSS Feed
* ========================================================================== */
function cloudzola_remove_version() {
return '';
}
add_filter('the_generator', 'cloudzola_remove_version');

Here are all code snippets combined

Just copy and paste it into the functions.php file for instant web page speed improvement. Please remove what you do not need, be aware if you already use optimization plugins.

/* ==========================================================================
*  Remove wp '?' version param from any enqueued scripts so it can be cached.
* ========================================================================== */
function cloudzola_remove_ver_css_js( $src ) {
if ( strpos( $src, 'ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
add_filter( 'style_loader_src', 'cloudzola_remove_ver_css_js', 9999 );
add_filter( 'script_loader_src', 'cloudzola_remove_ver_css_js', 9999 );
/* ==========================================================================
*  Remove Query Strings From Static Resources.
* ========================================================================== */
function _remove_script_version( $src ){
$parts = explode( '?', $src );
return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );
/* ==========================================================================
*  Load jQuery from Google API CDN Version 3.2.1
* ========================================================================== */
function cloudzola_google_jquery() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_enqueue_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', array(), true, true );
}
}
add_action('init', 'cloudzola_google_jquery');
/* ==========================================================================
*  Load jquery in footer 
* ========================================================================== */
function superfast_enqueue_scripts() {
wp_scripts()->add_data( 'jquery', 'group', 1 );
wp_scripts()->add_data( 'jquery-core', 'group', 1 );
wp_scripts()->add_data( 'jquery-migrate', 'group', 1 );
}
add_action( 'wp_enqueue_scripts', 'superfast_enqueue_scripts' );
/* ==========================================================================
*  Defer javascript - You can replace defer with async
*  Source: https://www.cloudzola.com/blog/eliminate-render-blocking-javascript-and-css-in-above-the-fold-content/
* ========================================================================== */
function cloudzola_js_defer_attr($tag){
# Add async to all remaining scripts
return str_replace( ' src', ' defer="defer" src', $tag );
}
add_filter( 'script_loader_tag', 'cloudzola_js_defer_attr', 10 );
/* ==========================================================================
*  Disable WordPress emoji support (added since WordPress 4.2) 
*  to prevent extra lines of CSS and JavaScript code in the head & loading additional javascripts.
*  This was added for extended support of emoji, removing the actions still let normal emoji works.
*  Remove if you need emoji support!
* ========================================================================== */
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
/* ==========================================================================
*  Remove wp-embed.min.js  and all other embedded scripts 
*  If you use Woocommerce or other dependencies remove this function!
*  This was added by WordPress since Version 4.4 & loads wp-embed.min.js in the header.
*  This disables all WordPress default embed functions!
* ========================================================================== */
add_action( 'init', function() {
                       
// Remove the REST API endpoint.
remove_action('rest_api_init', 'wp_oembed_register_route');
                       
// Turn off oEmbed auto discovery.
// Don't filter oEmbed results.
remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);
                       
// Remove oEmbed discovery links.
remove_action('wp_head', 'wp_oembed_add_discovery_links');
                       
// Remove oEmbed-specific JavaScript from the front-end and back-end.
remove_action('wp_head', 'wp_oembed_add_host_js');
}, PHP_INT_MAX - 1 );
/* ==========================================================================
*  Hide admin bar except for admins
* ========================================================================== */
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
show_admin_bar(false);
}
}
/* ==========================================================================
*  Remove WordPress Version from header and RSS Feed
* ========================================================================== */
function cloudzola_remove_version() {
return '';
}
add_filter('the_generator', 'cloudzola_remove_version');

I personally only use this from all above tweaks

Just copy and paste it to your functions.php file if you wish, it helped me to gain 1% pagespeed in GT Metrix and eliminated the Defer parsing of JavaScript notice and went from 92% to 100% for this notice while gaining 0.2% page load time. Remember every website and theme is different. The rest is just fancy stuff I like to use. Have fun optimizing.

/* ==========================================================================
     *  Defer javascript - You can replace defer with async
     * ========================================================================== */
    function cloudzola_js_defer_attr($tag){
        # Add async to all remaining scripts
        return str_replace( ' src', ' defer="defer" src', $tag );
    }
    add_filter( 'script_loader_tag', 'cloudzola_js_defer_attr', 10 );
    /* ==========================================================================
     *  Hide admin bar except for admins
     * ========================================================================== */
    add_action('after_setup_theme', 'remove_admin_bar');
    function remove_admin_bar() {
        if (!current_user_can('administrator') && !is_admin()) {
            show_admin_bar(false);
        }
    }
    /* ==========================================================================
     *  Remove WordPress Version from header and RSS Feed
     * ========================================================================== */
    function cloudzola_remove_version() {
        return '';
    }
    add_filter('the_generator', 'cloudzola_remove_version');

Use at own risk, you might gain a few points regarding pagespeed, check before and after to see your improvements.

Try those webspeed tests:

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.