Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

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

Parent Feed: 

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.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web