Last active
January 19, 2018 22:27
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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