I've been having a hard time trying to figure out how to do this.

I have a large group of nodes ordered chronologically. I want to be able to randomly display one of the first five most recent nodes. The problem is that the only way Views seems to limit row numbers is through the pager function, which I am already using to display just one node. Another obstacle that I am encountering is that the time that the nodes are posted is random.

Is there some way to filter the view so that the SQL only returns the first 5 results?

I've Googled this to death and haven't been able to get anywhere. Any insight would be greatly appreciated!

Thanks;

-Ryan

Comments

damiankloip’s picture

You can still just limit the rows returned by the query, under pager options, you choose the 'Display a specified number of items' option. Is that what you need?

rbrownell’s picture

Thanks for your response.

I actually need to randomly display one of the first five nodes in the query. So the block will only display content from one node at a time, instead of displaying all five at once.

Do you have any ideas>

Thanks;

-Ryan

merlinofchaos’s picture

Status: Active » Fixed

There's no way to do this in SQL, actually, so you can't do it directly in Views.

The way I would recommend doing this is to set up your view to return the first 5 results. In in a hook_views_post_execute() hook, take $view->result and reduce it to just one result randomly with a piece of php code that looks like this:

$view->result = array($view->result[array_rand($view->result)]);

(Note: I haven't tested the above code, so caveats for bugs/typos).

rbrownell’s picture

Thanks merlinofchaos! I'll definitely look into this!

-R

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

Anonymous’s picture

Issue summary: View changes

Corrected spelling.