General
Getting & Giving Support
Administration
Design
- Tut. - Layouts and Themes
- Tut. - Navigation cookbook
- Tut. - How To section
Reference Material
Plugin Development
- Tut. - Writing a plugin
- Ref. - List of Events
- Ref. - Enabling cron jobs
- Ref. - PHPDoc
Core Development
- Ref. - PHPDoc
Press information
Wolf CMS books section
Getting random pages in Wolf
Introduction
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.
Code
There is more than one way to accomplish this, and two approaches are shown here:
PHP-based
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
mySQL:
$rand = $this->find('/articles/')->children(array('order'=>'rand()', 'limit'=>1));
SQLite:
$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!)
