Force JavaScript/CSS reload in WordPress themes

If you are developing with WordPress, specially creating theme, browser needs to load your latest changes. Here is a trick to force your browser to reload the script or style:

A helper function:

/**
 * Generates dynamic JS/CSS file version number for forcefully asset loading
 * 
 * @param string $file file name relative to theme directory
 * @return bool|int last file modification time
 */
function wedevs_asset_version( $file ) {
    //file path will be relative to the current theme directory
    $file_path = is_child_theme() ? STYLESHEETPATH : TEMPLATEPATH;
    $file_path = $file_path . '/' . $file;

    if ( !is_readable( $file_path ) ) {
        return;
    }

    return filemtime( $file_path );
}

Here, we are getting the last file modification time of a file (js|css) from your current theme directory and returning the value. To use this helper function, you need to call the function with relative file path to your theme.

Usage:

wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/scripts.js', array('jquery'), wedevs_asset_version( 'js/scripts.js' ), true );
wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/css/custom.css', array('style'), wedevs_asset_version( 'css/custom.css' ) );

One thought on “Force JavaScript/CSS reload in WordPress themes

  1. Interesting way of handling it. I might have to check that out. Since I always try to bump the theme version when I make changes, I’ve been doing it based on theme version number like this:


    $foo = wp_get_theme();

    wp_enqueue_style( 'grid', get_stylesheet_directory_uri() . '/css/grid.css', array(), $foo['Version'], 'all' );

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>