Creating a /random url

Hey there! So I currently have a page on my site that lists all episodes. On that page, alongside the pagination, I have a button set up to choose a random episode…

<?php $randumb = $page->children()->visible()->shuffle()->first(); ?> <a class="randumb" href="<?php echo $randumb->url(); ?>">random</a>

While this is pretty good, it’s not ideal, because if you do browser-back, you’ll get the same URL linked. Also, I’d really love a persistent URL that’ll always pull in a random episode, and I’m not sure how I could make that happen. Suggestions appreciated.

For reference, the current random button is here.

Would this be possible if the logic was in a custom route instead of in the template code?

I agree with @samnabi, either a custom route or you create a new page folder, e.g. random with a text file random.txt in it and then create a template with your shuffle logic. In your href, you simply call the random page.

I think the browser back button will always give you the same page (without a reload) and with this the same link-url. So a custom route as @samnabi mentioned should work.

1 Like

That sounds like a great plan. I don’t suppose you could give me a nudge forward as to what kind of code would route to a random page from any page in one specific folder?

Something like this should work:

Your button:

  <a class="randumb" href="<?php echo url() . '/episode/random' ?>">random</a>

In your config.php

c::set('routes', array(
  array(
    'pattern' => 'episode/random',
    'action'  => function() {
    	$page = page('episode')->children('visible')->shuffle()->first();
     
      	go($page->url());
    }
  )
));
2 Likes

Or if you want to keep the url episode/random instead of redirecting, you could replace

go($page->url());

with

return site()->visit($page); 

… nobody is as fast as @texnixe :wink:

2 Likes

This is absolutely perfect, thank you.

I’m using the code from @texnixe with the tweak from @flokosiol so that you can refresh on the page and get a new episode, and it doesn’t upset any of the social actions or comments thread, so this a flawless solution. Thank you both.