I would like to create a block on my homepage where I show my visitors the most recent node (of a specific content-type) I've created. The block should load the 5 most recent nodes but only show one of them on page load.

I've managed to show a random product on page load, but the views takes a random node from all my nodes of that content-type. Is there a way I can limit the nodes, where the random block can chose from, to 5?

2 Answers 2


I wasn't able to get this working within views proper, so I added a subquery instead.

There are three relevant things that need to be set up in your initial view to get this to work:

  1. Filter Criteria: Content: Type = 'my content type' (blog post in the attached image)
  2. Sort Criteria: Global: Random
  3. Pager: Use Pager: Display a specified number of items: 1

UI of view

As it is, that will get you a view that will pull in 1 random result from among all content of type "my content type".

But the question is asking you to pull in 1 item from the last 5 created posts, not from all posts.

To do that, you need to add an additional where condition. That can be accomplished with this snippet:

 * Implements hook_views_query_alter().
 * Limits results to the most 3 recent blog posts.
function MY_MODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'MY_VIEW_NAME' && $view->current_display == 'MY_CURRENT_DISPLAY') {
    $query->add_where_expression('AND', "node.created > (SELECT node.created AS created
      node node
      WHERE  (type = 'MY_CONTENT_TYPE')
      ORDER BY created DESC
      LIMIT 1 OFFSET 5)");

That snippet says: "Find me the creation timestamp of the node that is the fifth-newest. Then filter my final result by nodes with creation timestamps greater than that."

There might be a better way, but this works for me.


I know it's probably too late, but in the 'Pager' section, you can use a pager and 'Display a specified number of items'. You can choose to display 5 items and then in the 'Sort Criteria' section sort by the 'Post Date'.

This way the view will only look at the 5 most recent posts and then randomly choose from one of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.