Multiple views in just one PHP tag

Last modified: January 21, 2008 - 14:49

After praising the Create multiple Views on one node with paging post into the skies (which I still do), I want to add my findings on this and also give a solution to avoid having multiple PHP-"Wrappers" around the individual views:

The reason why you needed to separate each View with its own PHP tag is quite simple:

Remember you were setting up a variable with a particular view in it:

// This calls our first secondary View.
// Change the View name within the parenthesis.
$view = views_get_view('home_page_new_groups');

So you told Views to get a view - the one in ('...') - right?! You were assigning the result to the variable $view !

In the next View you add, you do just the same thing, so basically you are again assigning $view with a particular value. So in the end, you have multiple $view variables with multiple content (or Views for that matter) in it.

It would be a bit more streamlined, if you did it like this:

<?php
// This loads all the variables of the primary view,
// including arguments which are in $current_view->args
global $current_view;

// Now let's call ALL desired additional views for this (you can add more
// if desired, just make sure to give each a unique variable name.
$view_1 = views_get_view('home_page_new_groups');
$view_2 = views_get_view('home_page_popular_groups');
$view_3 = views_get_view('home_page_new_content');

// This is some structuring HTML
print t("<br />");
print
t("<h2>Newest Groups</h2>");

// Build and print the view: first tell Views to embed the next view,
// then tell the function WHICH view you mean (you have defined
// this in the variables $view_1, $view_2 and $view_3 above.
// Next, pass into these views the Arguments from the primary view
// which you retrieved with global $current_view; and last but not
// least, "true, 10" enables paging and pages after 10 nodes are listed -
// change this number to whatever you need.
// So let's start outputting the first view:
print views_build_view('embed', $view_1, $current_view->args, true, 10);

// This is again some structuring HTML
print t("<p>&nbsp;</p>");
print
t("<h2>Most Popular Groups</h2>");

// Build and print the next view
print views_build_view('embed', $view_2, $current_view->args, true, 10);

// This is again some structuring HTML
print t("<p>&nbsp;</p>");
print
t("<h2>Most Popular Groups</h2>");

// Build and print the next view
print views_build_view('embed', $view_3, $current_view->args, true, 10);

// Continue adding views if you have set them up and assigned a
// unique variable above
?>

I hope that this example also clarifies a little more how to embed views in general! And as usual with PHP, be careful to end each line of instructions with a semicolon ;-)

 
 

Drupal is a registered trademark of Dries Buytaert.