Programmatically Create and Enable a view mode for a entity in Drupal 7

Last updated on 28/03/2016

A view mode is defined in HOOK_entity_info_alter.

/**
 * Implements hook_entity_info_alter().
 */
function HOOK_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes'] += array(
    'view_mode_name' => array(
      'label' => t('View mode name'),
      'custom settings' => FALSE,
    ),
  );
 
  return $entity_info;
}

Where "view_mode_name" is the machine name of the view mode you want to add (e.g: article).

The code bellow will enable the view mode for a specific bundle.

The code can be added in a hook_update(), hook_install() or hook_enable().

$settings = field_bundle_settings('node', 'article');
$settings['view_modes']['view_mode_name']['custom_settings'] = TRUE;
field_bundle_settings('node', 'article', $settings);