Passing an argument to a view is straightforward if the view is a page or if it is a displaying as a view field. If the view is a page, you can pass arguments through the URL. If the view is displaying as a view field, the view field module has an argument field. However, it is very difficult to pass an argument to a block view.
I was attempting to create a block of random images on each page that corresponded to the taxonomy term of the current page. (e.g. if the page was categorized as 'Spanish,' I only wanted 'Spanish' photos to display. If a page did not have a category, any type of photo could display.
There are a couple of options for accomplishing something like this. You can try to use the Views Argument API module. I tried to use it but was unsuccessful in making it work. You can write argument handling code. Or, you can build the view manually using views_build_view(). I chose the last option.
First, I created a block view that took an argument of taxonomy term id. The default for the argument was 'display all values.' This means that if a page has no taxonomy terms, all types of pictures will display. The sort order was random so that the pictures would display randomly.
Then, I created a block to call my block view. This allowed me to manually add whatever arguments I wanted. I set the input format for the block to PHP code and added the following lines:
$view = views_get_view('image_block');
if (arg(0) == 'node' && is_numeric(arg(1))) {
$categories = taxonomy_node_get_terms_by_vocabulary(arg(1), 1);
$i = 0;
$view_args = array();
foreach ($categories as $category) {
$view_args[] = $category->tid;
}
print views_build_view('block', $view, $view_args, false, 3);
}
else {
print views_build_view('block', $view, array(), false, 3);
}
First line - I call the block view I created using the view name.
Second line - I check to see if this is a node and parse the node id out of the URL. If it is not a node, I still call the view, but I don't add an argument.
Third line - I get the terms for the current node using the node id.
Fourth to eighth lines - I build an array of arguments.
Ninth line - I build the view using the argument array that I generated.