MODx Redirect to random child

My first MODx snippet and first real php written

I recently had a requirement that when a user clicked on a particular menu item they were redirected to a random child contained within that document. I couldn't find anything out there that already did this so I decided to set about making my first ever MODx snippet. Now although I'm a huge fan of MODx I've never really used php beyond reading over peoples code/snippets and I'm happy to say that it really wasn't too tricky. The full snippet can be found below, I'll submit it to the MODx repositories once I've tidied it up a little.


<?php
/*
 * @name RandomChildRedirect
 * @author Tom Dutczak-Smith <modx@tsmith.org.uk>
 * @Jason Coward <jason@opengeek.com>
 * @license Public Domain
 * @version 1.0
 * @Description: <strong>1.0</strong> Automatically redirects to a random child of a Container Resource
 *
 * This snippet redirects to a random child document of a folder in which this
 * snippet is included within the content (e.g. [RandomChildRedirect! ]). It is based
 * on the FirstChildRedirect snippet by Jason Coward. 
 * 
 * Parameters
 * 
 * &docid=`x` 
 * Use the docid parameter to have this snippet redirect to the
 * first child document of the specified document.
*/
$docid = (isset($docid))? $docid: $modx->documentIdentifier;

$children= $modx->getActiveChildren($docid, 'menuindex', 'ASC');
if (!$children === false) {
    $randChild= $children[rand(0,count($children)-1)];
    $randChildUrl= $modx->makeUrl($randChild['id']);
} else {
    $randChildUrl= $modx->makeUrl($modx->config['site_start']);
}
return $modx->sendRedirect($randChildUrl);
?>

Write a comment

  • Required fields are marked with *.

If you have trouble reading the code, click on the code itself to generate a new random code.
 
Sepia River
Posts: 3
Comment
Sweet!
Reply #4 on : Tue March 22, 2011, 09:23:52
This is just what I needed. Thanks Tom!
Tom
Posts: 1
Comment
RE: Redirect
Reply #3 on : Wed December 01, 2010, 20:25:50
Hi Stephen,

Your code is fine if all the children of a container have sequential id's between 2 values but typically in a site that's built up over time you're more likely to find that a containers ID's won't be sequential at all ie (4,34,99,106) in which case your function wouldn't work.

Cheers, Tom.
Stephen O'Neil
Posts: 3
Comment
Redirect
Reply #2 on : Thu October 21, 2010, 00:25:16
Try this mate:

this is your snippet call and this is the code:

$modx->sendRedirect($modx->makeUrl(rand(6,8)))

6,8 is the range of document ids to be randomized.

Thanks for the inspiration.
Eric
Posts: 3
Comment
Thanks man
Reply #1 on : Fri October 08, 2010, 01:19:08
I wanted to do this myself. Thought I'd try google and found this page. Cheers.