Skip to main content

Drupal 8: How to disable or stop a specific block from being cached

If your  block in Drupal 8 needs to update its contents every time there is a page load then you need to disable the cache for the specific block.

You can replace themeName with your custom module name and the $vars['plugin_id'] with just $vars['id'] or $vars['derivative_plugin_id'] whatever makes more sense for your logic.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function themeName_preprocess_block(&$vars) {
  if($vars['plugin_id'] == 'your-block-id') {
    //-- This stops the block being cache in drupal 8
    $vars['#cache']['max-age'] = 0;
  }
}

 

block