Light-weight, fast, simple and powerful!
Translations of this page?:

Getting random pages in Wolf


It is sometimes useful to be able to display things “randomly”: banner pictures, quotes, articles, and so on. Here is one technique to do this in Wolf. This approach grabs a random entry from an array of “child” pages to some parent page.

The example below demonstrates how to grab a random article as a convenient place to start.


There is more than one way to accomplish this, and two approaches are shown here:


Create a “child” to the Home Page (let's call it “Random Article”), and paste this into the body of the page, leaving the text filter set at -none-:

<?php $randarts = $this->find('/articles/')->children(array());
$randart = array_rand($randarts, 1); 
$rand = $randarts[$randart]; ?>

The first line gets the child pages as an array; the second line uses the PHP array_rand() function to select a random entry; and the third line sets a variable for that entry for later use.

Using Database functions


$rand = $this->find('/articles/')->children(array('order'=>'rand()', 'limit'=>1));


$rand = $this->find('/articles/')->children(array('order'=>'random()', 'limit'=>1));

These examples get the array of Articles, as in the PHP-based example above, but use native database functions to randomize the array before selecting the specific random article.

[HT: Sartas ]

Putting it to work

Whichever method you use, you can now use the $rand variable with a whole variety of Wolf functions. For example, continuing on the “Random Article” page, you could include a link to the “normal” URL of the random page, its publication date, plus its content like this:

<h3><?php echo $rand->link(); ?></h3>
<p><span class="info"><em>Originally published</em> <?php echo $rand->date(); ?></span></p>
<?php echo $rand->content(); ?>

Each time the “Random Article” page is loaded, a different random (surprise!) article will be displayed.

The same technique could be used for banner pictures, by having a hidden “banner-pics” page, and having each of its child pages contain the img code for a different image.

(Feel free to extend this page with other examples or different approaches!)

tutorials/random_things.txt · Last modified: 2011-09-12 00:46 (external edit)
Except where otherwise noted, content on this wiki is licensed under the following license:GNU Free Documentation License 1.2
Copyright 2010 / design by yello studio / Wolf CMS Inside