3 Ways to easily stop wordpress caching your stylesheets

In this post I’m going to tell you how to easily stop WordPress from caching your css styles, so changes you make are instant. It can be very handy todo this while you are testing your new website.

Stop WordPress caching styles (the quick and easy and dirty way)

The first way and the quickest is to just pop them into header.php after wp_head() has run, so you know your styles are definitely the last css loaded (unless of course there are inline styles in the page). You do this like so:

<head>
  ...
		<?php wp_head(); ?>

                
                <style type="text/css"> 

                    #bottom_logo{
                        position: relative; left: -20px;
                    }

                    @media screen and (max-width: 768px) {
                    #bottom_logo{

                        padding-bottom: 20px;

                    }

                }
                </style>
	</head>

Stop WordPress caching stylesheets (the quick and easy way)

The next way is to keep your css styles in a stylesheet (which is abit nicer). You do this by making a separate stylesheet including your stylesheet last ( and trick the browser to reload it everytime the page is loaded ). You do this like so:

<head>
...

	<?php wp_head(); ?>

	<link rel='stylesheet' href='<?php echo get_stylesheet_directory_uri();?>/mystyles.css?counter=<?php echo time(); ?>' type='text/css' media='all' />

</head>

What we did here is add the following to the url for our stylesheet ?counter=<?php echo time(); ?>

What does this do I hear you ask? This adds a unique number to the href everytime, this tricks the browser into thinking we’re loading a new file each time ( so we get fresh css everytime , no caching ever !). Basically the url for the stylesheet looks something like this: http://somedomain.com/wp-content/themes/mytheme/mystyles.css?counter= 1403257044

Stop WordPress caching stylesheets (the slightly more techie way)

The third and final way is to edit / add a style where WordPress loads it (if its loaded this way and not in header.php ) , you do this like so (usually in functions.php ). You will see we are passing time() to the function wp_enqueue_style, this appends it to the url to force wordpress to reload the file:

wp_enqueue_style( 'louiscss', get_template_directory_uri() . '/mystyles.css', array(), time() );

So I hope these tips help anyone struggling with WordPress and not sure if its WordPress or the styles that are the issue, when adding or editing your HTML and CSS.

5 thoughts on “3 Ways to easily stop wordpress caching your stylesheets”

  1. Nice writeup. I usually do this which never seems to have issues.

    function load_custom_styles() {
    $bw_theme_dir = trailingslashit(get_stylesheet_directory_uri());
    $file = $bw_theme_dir . ‘css/custom.css’;
    if ( file_exists( $file ) ) {
    echo ” . file_get_contents($file) . ”;
    }
    }

    Reply

Leave a Comment