Drupal - Preprocess variables only for certain blocks

Unfortunately, there is no way to do it like that (similar to hook_form_alter()).

The best way to do this would be to use $variables['block']->bid to apply modifications only to the blocks you want:

function mytheme_preprocess_block(&$variables) {
  if ($variables['block']->bid === 'target_block_id') {
    // do something for this block
  } else if ($variables['block']->bid === 'other_target_block_id') {
    // do something else for this other block
  }
}

Just to confirm, in Drupal 8 you can write preprocess functions for specific blocks. For example:

Drupal 8

mytheme_preprocess_block__system_branding_block(&$vars) {
  // Make changes to the the system branding block
}

But you could also use hook_preprocess_block, and the plugin ID:

function mytheme_preprocess_block(&$vars) {
  if ($vars['plugin_id'] == 'system_branding_block') {
    // Make changes to the the system branding block
  }
}

As mentioned by Alex, in Drupal 7 you'll have to stick with HOOK_preprocess_block, and an id check:

Drupal 7

mytheme_preprocess_block(&$vars) {
  if ($vars['block']->bid === 'target_block_id') {
    // make changes to this block
  }
}

Tags:

Blocks