5 August 2023

In Drupal 7, you can use the hook_entity_view_alter() function to alter the rendering of entities before they are displayed. This hook allows you to modify the display of entity content without directly manipulating the entity's template files.

Source code viewer
  1. /**
  2.  * Implements hook_entity_view_alter().
  3.  */
  4. function HOOK_entity_view_alter(&$build, $type) {
  5. if ($type == 'node') {
  6. // Check if the entity is of a specific bundle (content type).
  7. if ($build['#bundle'] == 'article') {
  8. // Modify the way the article nodes are displayed.
  9. // For example, you can add a custom class to the entity's HTML wrapper.
  10. $build['#attributes']['class'][] = 'custom-article-class';
  11.  
  12. // You can also add additional content to the entity's display.
  13. $build['my_custom_field'] = array(
  14. '#markup' => 'This is a custom field added by the entity view alter.',
  15. '#weight' => 10,
  16. );
  17. }
  18. }
  19. }
Programming Language: PHP