Hello,

I'm trying to build a block view that displays the 5 latest nodes in random order but I'm having difficulties to find the good way to do that.

I have:
-5 items to display
-filters for no sticky but promoted nodes
-in the sort criteria:
1. updated/commented date
2. global random

but offcourse the problem is that the nodes are already ordered by date and the 'random' sort doesn't do anything anymore...

Somehow I will have to do a subquery I imagine. Possible with the views module?

Comments

merlinofchaos’s picture

Status: Active » Fixed

You don't need to do a subquery, instead what you need to do is shuffle the nodes prior to displaying them. The easiest way to accomplish this would be to implement THEME_preprocess_views_view__VIEWNAME() and use array_rand() to randomize the order.

Hopefully this is enough to point you in the right direction.

Status: Fixed » Closed (fixed)

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

xsean’s picture

hi merlinofchaos,

can you provide example code in THEME_preprocess_views_view__VIEWNAME()?

the view name is which name as there are default, page 1, page 2, block 1 and block 2?

hope can hear from you soon. thank you

akalata’s picture

I've made some progress based on merlin's direction, but I'm having trouble figuring out how to return the re-ordered rows to the view. Maybe I'm shuffling the wrong array?

/**
 * Preprocessor for view template views-view--MYVIEW--VIEWDISPLAY
 */
function mytheme_preprocess_views_view__myview__block(&$vars) {
	//dsm($vars['view']->style_plugin->rendered_fields); // how I found the array to order
	$listings = $vars['view']->style_plugin->rendered_fields; 
	dsm($listings); // un-shuffled array
	shuffle($listings);
	dsm($listings); // shuffled array
	$vars['view']->style_plugin->rendered_fields = $listings; // trying to send shuffled array back to the view
}
merlinofchaos’s picture

The order will be determined by $view->result most likely, and $view->rendered_fields just gets referenced by indices. If you just shuffle $view->result and make sure the keys are retained, it should be fine.

akalata’s picture

Thanks for the response!

I'm not quite sure what you mean by "make sure the keys are retained." Do you mean that the auto-assigned, zero-indexed keys need to be retained?

Example:
Not-shuffled returns auto-keyed with the following nids

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

After shuffle()'ing the array, the result is

Array
(
    [0] => 3
    [1] => 4
    [2] => 1
    [3] => 5
    [4] => 2
)

Instead, does the shuffled array need to be

Array
(
    [2] => 3
    [3] => 4
    [0] => 1
    [4] => 5
    [1] => 2
)

? I'm not sure that the second result is even possible, since according to http://www.php.net/manual/en/array.sorting.php the random sort does not maintain key association. However, I'm reaching the limit of my PHP knowledge, so it's probably just coder error.