Outputting a Drupal 7 View programmatically with Contextual Filters (arguments)

By shane
Fri, 2012-09-07 17:18

Share with Others

Ever need to output a Drupal 7 view in your code? If so the views_embed_view function is an easy way to do this. One thing you may not have known, is that you can also use it to pass values into your views contextual filters (what the Drupal views module used to call "arguments").

Here is a quick example of how to output a view in code using the views_embed_view function:

print views_embed_view('VIEWS_MACHINE_NAME', 'DISPLAY_ID');

You can get the VIEWS_MACHINE_NAME by going to the main views listing and hovering over the Drupal 7 View you are trying to output programmtically. This should give you a tooltip with the Views machine name.

You can get the display_id by editing that view and hovering over the tab that you want to display. In the URL that is generally displayed on the bottom left of most browser you will see something like this:


In this example, the display id is "block_2" and the machine name is "my_test_view".

If you want to send an argument into the views contextual filter, simply add another argument to the views_embed_view function.

$my_arg = 1;
print views_embed_view('my_test_view', 'block_2', $my_arg);

Side Note: If you are using a date as a contextual filter (as I was in my case), the format of the date is YYYY-MM-DD. So an example would be:

$my_date = "2012-09-07";
print views_embed_view('my_test_view', 'block_2', $my_date);

What do you think? Let me know in the comments below.

P.S. if you are wondering what all this code is and just want to learn more about views, check out our views intro.