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
Posts: 3
Reply #4 on : Tue March 22, 2011, 09:23:52
Posts: 1
Reply #3 on : Wed December 01, 2010, 20:25:50
Posts: 3
Reply #2 on : Thu October 21, 2010, 00:25:16
Posts: 3
Reply #1 on : Fri October 08, 2010, 01:19:08