TwentyTwelve versioning

How it’s NOT done in WordPress

The following example is the opposite of how one should do it. Bad practice following:

<style type="text/css">
<!--
/* ... Definitions that are hard to override or get rid off are here ... */
-->
</style>

This is another example how you should not do it:

<link rel="stylesheet" type="text/css" href="https://wordpress.stackexchange.com/questions/90393/style.css">

Do it right

WP uses a “dependencies” API for managing script and style files. This means that you

  1. Register
  2. Enqueue
  3. (optionally, and for scripts only) Localize

This means that you first go and register a script for further usage and then enqueue it. This way you can register a stylesheet or script in your parent theme or plugin and later on enqueue it and print it to your webpage on demand.

How to prevent caching

This API as well has one nice little argument for versions. This means, that you have a variety of options how to update your browser or server cache, as the version gets added to the query string when loading the file:

  • manually add a new version string every time you write an update
  • Using the date() or time() (or similar DateTime) functions to permanently update
  • Use filemtime( get_stylesheet_directory()."https://wordpress.stackexchange.com/questions/90393/style.css" ) to **only change the version when you did an update.
  • And finally there’s the technique of “filename based cache busting” that actually alters the filename if there were changes. It needs some .htaccess modifications as well.

Example

This one’s taken from a plugin I’m currently developing:

$file="js/chained_selection.js";

wp_register_script(
     $this->handle
    ,plugin_dir_url( __FILE__ ).$file
    ,array( 'jquery',  )
    ,filemtime( plugin_dir_path( __FILE__ ).$file )
    ,true
);
wp_enqueue_script( $this->handle );

wp_localize_script(
     $this->handle
    ,"{$this->handle}_obj"
    ,array(
         'ajaxurl' => admin_url( 'admin-ajax.php' )
        ,'nonce'   => wp_create_nonce( $this->ajax_nonce_val )
        ,'action'  => $this->action
    )
);

When to load the stylesheet/script

Normally one simply wraps the register/enqueue/localize statements into a function or class method. To allow others jump in at the right point, the hooks used for styles and scripts are the following:

  • admin_enqueue_script // Admin UI
  • wp_enqueue_script // Themes
  • login_enqueue_script // Login pages