Drupal - How do I programmatically show a view block?

Use views_embed_view():

echo views_embed_view('view_machine_name', 'block_1');

You can find out the display name by clicking the tab and check its name in the address bar of your browser: #views-tab-block_1 gives you block_1.


If you want to pass a parameter to the view use:

echo views_embed_view('view_machine_name', 'block_1', $param);

For example:

echo views_embed_view('view_machine_name', 'block_1', $node->nid);

or:

echo views_embed_view('view_machine_name', 'block_1', $nid, $uid);

tostinni's answer is the correct one in most cases. However, if you want to include the View title, it is a bit more ugly.

From the views_embed_view() documentation:

Note that this function does NOT display the title of the view. If you want to do that, you will need to do what this function does manually, by loading the view, getting the preview and then getting $view->get_title().

For example:

$name = 'view_machine_name';
$display_id = 'block_1';
$view = views_get_view($name);
if (!$view || !$view->access($display_id)) {
  return;
}
$view_content = $view->preview($display_id);
$title = $view->get_title();

Updated: @rojosnow noted that the docs point out you must get the preview before calling get_title() so I've flipped those two lines around.

Tags:

Views

7

Blocks