Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active January 19, 2018 22:27
Show Gist options
  • Save aklump/7ac65637b683913cb4638cba0f744259 to your computer and use it in GitHub Desktop.
Save aklump/7ac65637b683913cb4638cba0f744259 to your computer and use it in GitHub Desktop.
How to add cache-busting to itok image derivative urls in Drupal 7 for entity image fields.
<?php
function my_module_node_view_alter(&$build)
{
if (!empty($build['field_image']) && user_is_logged_in()) {
$build['field_image']['#post_render'][] = 'my_module_cache_buster';
}
}
function my_module_cache_buster($html, $build)
{
global $user;
$buster = array(
// The query string key is 'cb='
0 => 'cb',
1 => null,
);
if ((!empty($build['#object']->changed))) {
$buster[1] = $build['#object']->changed;
}
elseif ((!empty($user->access))) {
$buster[1] = $user->access;
}
else {
$buster[1] = time();
}
$regex = '/' . preg_quote(IMAGE_DERIVATIVE_TOKEN) . '[^"]+/';
$html = preg_replace($regex, '$0&' . implode('=', $buster), $html);
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment