treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Prevent CSS Caching

Last updated on:

WordPress:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); echo '?' . filemtime( get_stylesheet_directory() . '/style.css'); ?>" type="text/css" media="screen" />

bbPress:

<link rel="stylesheet" href="<?php bb_stylesheet_uri(); echo '?' . filemtime( bb_get_active_theme_directory() . '/style.css'); ?>" type="text/css" media="screen" />

Adds stylesheet with time of last update. If the number changes the browser updates the CSS instead of using cached version. Easily amended to be none WP specific.

View Comments

Comments

  1. In WordPress,

    filemtime(get_bloginfo( 'stylesheet_url' ));

    Will fail, apparently because get_bloginfo('sylesheet_url') returns an absolute path and that upsets the filemtime() function.

  2. Permalink to comment#

    I’m trying to move a website to a different server, downloaded all the files the new company put them up for me but I have lost all my css formatting for my theme (striking). Can find where the original developer of the website make the changes to header sizes, link colours etc etc. Could you help me maybe. Please

  3. Permalink to comment#

    And for your JS…

    
    <script type="text/javascript" src="<?php echo get_bloginfo('template_directory') . '/js/script.js?' . filemtime( get_stylesheet_directory() . '/js/script.js');?>"></script>
    
  4. Christian Sciberras
    Permalink to comment#

    Agustin….on the contrary…it fails because it returns a path relative to document root…

  5. Martin Klasson
    Permalink to comment#

    I am getting a “Stat”-php error for the example given above.
    The solution that I worked out that was working for me was this:

    <link rel="stylesheet" href="/css/style.css?version=”>

    What I have done is used the dirname(_FILE_) to get the path to the directory. Not the URL, but the PATH on the computer.

    The code above is used for my custom css-class. (I dont use the default css), but can easily be amended of course to work along with the stylesheet_url as well.

  6. Murdoc
    Permalink to comment#

    Thank you, sir! This is exactly what I have been looking for!

  7. Permalink to comment#

    There is a plugin up on the WordPress Plugin Repository that takes care of this automatically. Fixes version numbers for stylesheets and scripts. WordPress plugin Versions. Works really good.

    • scott

      only problem is it renders your site completely blank. uninstalled. thanks for the panic.

Leave a Comment

Use markdown or basic HTML and be nice.