Drupal - How can I programmatically copy all blocks of a given theme into the same regions of a new theme?

You can entity query your relevant block config then create a cloned entity object via Block::createDuplicateBlock() then modify the sub-theme clones before saving the new block config into sub-theme region.

For example:

$block_ids = \Drupal::entityQuery('block')->condition('theme', 'my_base_theme')->condition('region','my_region')->execute();
foreach ($block_ids as $block_id) {
  $parent_block = \Drupal\block\Entity\Block::load($block_id);

  $new_id = str_replace('my_base_theme', 'my_sub_theme', $parent_block->get('id'));
  $child_block = $parent_block->createDuplicateBlock($new_id, 'my_sub_theme');
  // @TODO: set other properties that might need to be unique to this new theme's block

  $child_block->save();
}

Tags:

8

Blocks