Using custom php in a views header or footer

Sometimes you want to use PHP in a views header or footer. If so, DO NOT use views_php but alter it programatically using the hook_views_pre_view. See below for various examples.

* hook_views_pre_view
function mymodule_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'myview' && $view->current_display == "my_display") {
    $fact = get_random_fact();
    $options = array(
      'id' => 'area',
      'table' => 'views',
      'field' => 'area',
      'empty' => FALSE,
      'content' => '<a href="/example" class="button-primary">Did you know ' . $fact . ' </a>',
      'format' => 'full_html',
      'tokenize' => 0,
    $view->display_handler->set_option('header', array('text' => $options));

if you want to add something instead of replacing it use:

$view->add_item('my_display', 'header', 'views', 'area', $options);

Also possible: using hook_views_pre_render or hook_views_post_execute, and/or using attachments:

    $content = 'Lorem ipsum';
    $view->attachment_before = $content;


This is the company blog of
Drupal specialist

We are located in Breda (Netherlands) and build websites using Drupal. More about us.

Content on this blog is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Netherlands License.

Creative Commons License

Recent Comments