[Drupal] How to rewrite the output of a view using hook_views_post_render?

| | 1 min read

If you are searching for a way to alter the output of a View after it has been rendered, you may find this article to be helpful. We had recently come across a situation which forced us to rewrite the rendered output from a View and we managed to find a useful hook - hook_views_post_render. It helped us to rewrite the output of the view. If you are facing the same situation in your Drupal site and would like to know how to rewrite the output of a View using hooks_views_post_render. then continue reading.

Follow the steps below

  • Create the View and add the hook_views_post_render inside your module file.
  • Inside this hook you will be able to get the rendered data in the $output variable.
  • The fields in the View are available as tokens inside this hook. For example, [nid] for nid & [title] for title. You will be able to replace these tokens with your custom variables.
  • In the example cited below, node/nid is replaced with a custom tag.
    function custom_views_post_render(&$view, &$output, &$cache) {
      if ($view->name = 'View_name') {  	
        $v = '<a href="test">test</a>';
        $s = strtr($output, array('node/[nid]', $v));
        $output = $s;
      }
    }

It is quite easy to try this out. Give your feedback regarding the comment form below