Page 1 of 1

display random child

Posted: Thu May 05, 2011 9:58 am
by dwave
Hello,
I'd like to share a code snippet to grab/display a random child with cgsimple:

Code: Select all

{$cgsimple->get_children('parent_alias',0,'children')}
{assign var=randomindex value=$children|@array_rand} 
The parameter 'parent_alias' is just the page alias of the parent whose children you want. The variable $randomindex will contain a random index from the array $children from the PHP function 'array_rand' as modifier. It's as simple as that (tested with 1.9.4). No awkward loops are needed!

Then you can access the child's content with the usual cgsimple methods, e.g:

Code: Select all

{$cgsimple->get_page_content($children.$randomindex.alias,'field', 'myvar')}
In the example above I'll write the content of the field 'field' into variable 'myvar'. And print it:

Code: Select all

<span> {eval var=$myvar} </span>
I hope this helps. It took me a while to figure it out but with a bit of Smarty magic CMS Made Simple can be used for quite powerful, flexible (and simple) content customizations. Thanks again for the developers for their ongoing effort.

Re: display random child [SOLVED]

Posted: Wed Feb 08, 2012 4:33 pm
by mesaredo
I dwave:

Could you indicate where you place each code (template, page, etc..) Thank you!

Re: display random child

Posted: Fri Feb 10, 2012 3:06 pm
by dwave
Mesaredo,
this Smarty snippet works in templates as well as in Global Content Blocks. Make sure that the module CGSimpleSmarty is installed, so that the class cgsimple is available.

Another example to display a random title from one of the child pages of the page "parent":

Code: Select all

{$cgsimple->get_children('parent',0,'children')}
{assign var=randomindex value=$children|@array_rand} 
{$cgsimple->get_page_title($children.$randomindex.alias, 'title')}
{eval var=$title}