Display 3 random blog items

Is there an easy way to get a collection of three random blog items inside a partial without a plugin?

Use taxonomy.find or page.parent.collection to get the list of pages. Then randomize filter to shuffle it. Then slice filter to shorten the list to length.

Sorry can’t really type the code on my iPhone :slight_smile:

Thanks for the fast reply! I was experimenting with taxonomy.find however I can’t seem to randomize it. I’m probably doing the randomize wrong.

I used this for testing:

{% set random_articles = taxonomy.findTaxonomy({'category':'blog'})|randomize %}
                    {% for post in random_articles %}
                        <li>{{ post.title }}</li>
                    {% endfor %}

Ok, this is even easier than I originally thought :slight_smile:

{% set random_articles = taxonomy.findTaxonomy({'category':'blog'}).random(3) %}

I had forgotten, so had to dig into the code. The trick was to look into the Collection class and see available methods. Not finding anything useful, I looked at the Iterator class which Collection extends. In there was a very handy random() method :slight_smile:

Wow thanks! Didn’t know you could give a value to random(), super easy!

Is there a similar method to get the 3 most recent articles in a partial?

it’s not the same thing, but it can be done with a collection. Collections support sorting and ordering. something like:

{% set recent_articles = page.find('/blog').collection.toArray|split(0,3) %}

Untested, but I think that should work.

Collection has also other useful functions like:

collection.slice(0, 3)

So in this case I would just use:

{% set recent_articles = page.find('/blog').collection.slice(0,3) %}

Good call!

Just wondering. Did you get the display of 3 random articles to work? If so, is there some place I could look at it? I’m wrestling with the same problem myself, trying to surface and present one random article from the past (rather than a redirect with the Random plugin).