Wednesday 7 December 2011

Embed Drupal Views Using PHP

When theming Drupal and wanting to output a view there are occasions where using a view display (e.g. a page, or a block - perhaps placed within a custom region ;-) ), or using Views Attach will not suffice.
Instead, you can embed a view using the following PHP snippet:
(NOTE: you'll need to have the core PHP input filter enabled if embedding in a node body)

<?php
$view
= views_get_view('VIEWNAME');
print
$view->preview('default'); 

?>
or, if you need to use an argument with the view:
<?php
$args
= array(ARGUMENTS);$view = views_get_view('VIEWNAME');
print
$view->preview('default', $args); 

?>

NOTE:
  • replace VIEWNAME with your actual view name - e.g. 'my_drupal_posts'
  • replace ARGUMENTS with the argument(s) your view is expecting - e.g. this may be a node id
The PHP snippets above will output your view's 'default' display. However, you can output other displays from your view (if your view has multiple displays) - e.g. to output a view's first block display you'd modify the snippet by replacing the Views display id 'default' with 'block_1' and use:

<?php
$args
= array(ARGUMENTS);$view = views_get_view('VIEWNAME');
print
$view->preview('block_1', $args); 

?>

No comments: