How to programmatically insert a view into a tpl or content in Drupal 6

In Drupal 6 views has been completely rewritten from the ground up, and as such we have to adjust the little code snippets that we developers have collected over the years to compensate.

The old way ( Drupal 5 views 1 ) of inserting a view into a tpl or into a php enabled content area was as follows:

<?php
$view_name = ‘text_listing’; //name of view
$view_args = array($oldstring) ;
$view = views_get_view($view_name);
print views_build_view(’embed’, $view, $view_args, $view->use_pager, $view->nodes_per_page);
?>

This has now changed to the following:
<?php
  $view_args = array();
  $display_id = ‘page_1’;
  $view = views_get_view(‘logo_slideshow’);
       if (!empty($view)) {
        print $view->execute_display($display_id , $view_args);
  }
?>

Now at first this might not seem much different, but watch out. There are some new pitfalls in views 2 that make this a little trickier to pull off.

The first problem comes into play when you try to figure out what to use for the display id. There are two ways that I have found to determine the display id. One is to go to that view and export it. Then look for a line of code that looks something like this:
$handler = $view->new_display(‘page’, ‘Page’, ‘page_1’);

I say “something like this” because the arguments inside of the new_display method may be different for your view if you have several displays or if you are only displaying a block version. Regardless of the type of display you have the information you need is the 3rd argument ‘page_1’ in this case.

I insert the code to create the view, and it works but now my page titles are gone! What gives?

Yes, this is a bizarre side effect of this technique, but there is a way around it. When this first happened to me I was stumped for about an hour because I had added it to a new content type and had just installed a new module, so I was sure that it was one of those factors that was messing it up, but then, after none of the changes I was making had any effect it dawned on me that perhaps views was calling Drupal_set_title from within the view. So to get around this I reset the title from within the tpl from within the same code as the view like so:
execute_display($display_id , $view_args);
 }

drupal_set_title($node-&gt;title);
?>;

The function Drupal_set_title() resets the title of the page to the node title.

So there you have it. You should now be able to include views into your tpls in all sorts of weird and unusual ways that were never intended. Good luck.