Ever since I started working on my Wildlife photo gallery in Drupal, I have been discovering the power of Views, which I seldom tap in time-bound projects. Here is an interesting trick that I would like to share.
The case is as follows. I have set up a Page using Views that displays photos based on criteria like species, location and type. The Views Page displays the thumbnails of the photos. Each thumbnail is linked to the Node page, which displays a larger photo and its details.
The page looks good and populated when I have lots of photos for each criteria. Unfortunately, in certain cases I do not have more than one photo displayed on the Views page. For example, I have only one photo of most species – since I started Wildlife photography just this year. As a result, the Views Page shows the thumbnail photo of just one species. This requires an extra, unnecessary click for the visitor to go to the Node page to see the larger photo and its details.
It makes sense to redirect visitors to the Node page if the View is displaying only one photo or node. So I started looking for ways to achieve the following in Views: If there is only one row (corresponding to one photo) then redirect visitors to the Node page which displays the larger photo.
And guess what – it requires only a few lines of code. While adding/editing the View, make sure you select Content:Nid, amongst other Fields.You may chose to exclude this field from the display.
Next, click on the add button (besides FOOTER). Select Global: Text Area. Click on Apply. In the textarea (the big box below Label) type in the following:
<?php global $base_url; if($GLOBALS['pager_total_items'] ==1) header("Location: $base_url/node/[nid]"); ?>
From the dropdown labelled Text format, select PHP Code. Note that the option PHP Code will be visible only when you enable the module PHP filter under Modules.
Next, check the box labelled “Use replacement tokens from the first row”. Click on Replacement Patterns and ensure that the token for Content:Nid is [nid]. If not, replace [nid] in the above code with the appropriate token. Click on Apply.
Note that the following code will work only if you have paging enabled in the View (PAGER> Use pager>Paged output). Save the View when you are done with other settings.
That’s all folks. This works in Drupal 7 with Views 3.3.