Is the theme customizer slowing down my site?

How often are the theme mods changed? A lot in the design phase, maybe a couple of times later on. Always by admins, never by ordinary users, let alone visitors. So, it doesn’t make sense to generate the full css at every pageload (additional background info).

A better approach is to generate the css only for the admin and store the result for others. This will reduce the amount of database calls from 500 to 1.

function mytheme_customize_css()
{
    if (current_user_can( 'edit_theme_options' ) ) {
         $assemble_css = "
         <style type="text/css">
             h1 { color:" . get_theme_mod( 'header_color', '#000000' ); . "; }
             h2 { color:" . get_theme_mod( 'tagline_color', '#ffffff' ); . "; }
             ... 498 more ...
         </style>";
         set_theme_mod( 'all_mods', $assemble_css );
    }
    echo get_theme_mod ( 'all_mods', '' );
}
add_action( 'wp_head', 'mytheme_customize_css' );

This is better, but how often will all 500 mods actually be used? And is it really ideal to have the default css values in this function in stead of style.css? Better move the defaults there and only generate a css line if there is a value. This gives:

function mytheme_customize_css()
{
    if (current_user_can( 'edit_theme_options' ) ) {
         $assemble_css = "
         <style type="text/css">";
         if ( get_theme_mod('header_color') ) $assemble_css .= "
             h1 { color:" . get_theme_mod( 'header_color' ); . "; }";
         if ( get_theme_mod('tagline_color') ) $assemble_css .= "
             h2 { color:" . get_theme_mod( 'tagline_color' ); . "; }";
         ... 498 more ...
         $assemble_css .= "</style>";
         set_theme_mod( 'all_mods', $assemble_css );
    }
    echo get_theme_mod ( 'all_mods', '' );
}
add_action( 'wp_head', 'mytheme_customize_css' );

If you actually have this many mods, it would be even better to assemble them in a datastructure and loop through it rather than have 500 lines in the function (and several thousand lines of code to add the sections to the customizer).

Also, writing the css directly to the head like this is not great. You should be using add_inline_style. But that’s another thing.

Leave a Comment