MODxAs I was posting a solution in the MODx forums this morning I realized that I have never posted the use of the randomDoc snippet here. This is a simple and useful snippet that I have used in many instances. It randomly returns a single document within a directory. You should have all the standard MODx fields (and I believe Template Variables too) available to you.

<?php
// snippet RandomDoc
// returns content from a random document
// from a given folder
// usage [!RandomDoc?folder=`xxx`!]
// if $folder is not set, uses current doc ID as folder
$folder = isset($folder)?$folder:$modx->documentIdentifier;
$docs = $modx->getActiveChildren($folder);
// get a random document id
$rnd = rand(1, count($docs));
$rnd -=1; // because we need to start at 0 in the array
$randomDocId = $docs[$rnd]['id'];
// get the content of the random doc
$contentRow = $modx->getPageInfo($randomDocId,1,'link_attributes,pagetitle, introtext,id');
$ret = '';
$ret .= '<span id="verse-title">'.$contentRow['pagetitle'].'</span><br />';
$ret .= '<span id="verse-content">'.$contentRow['introtext'].'</span>';
$ret .= '';
return $ret;
?>

This snippet hasn’t been developed to the point of having a tpl file available to control the output. To date I have hand code the output in the $ret section of the code.

You can see an example on the Valley View Church of Christ site. The snippet controls the Daily Bible Verse feature. On my sites I have found this to be a quick and easy solution for adding a nice random effect to a site.

  • jasonimani
    Thanks Greg! I've been putzing around the MODx repository for something like this...glad I saved this link from a long time ago.
  • Glad it helped.
blog comments powered by Disqus