How to display random forms with Textpattern
Here is the scenario; I was looking to output some data between the end of an article and just before the comments on an individual articles page. So the page structure would look like Title > Article > New Data > Comments. How do you accomplish this? I cheated and asked Textpattern developer Ruud van Melick for help…
Textpattern tacks on the Comments section after an article for you which is really helpful. To display something at the end of an article before the comments you can use the
txp:if_individual_article tags at the bottom of your default article form. But what if you wanted to display a random article? Say ‘form1’, ‘form2’ or ‘form3’? This is the code that Ruud sent my way:
$forms = array('form1', 'form2', 'form3');
echo output_form(array('form' => $forms[rand(0, count($forms)-1)]));
- Download this code: /code/txp_randomform.txt
This is pretty straight forward and worked first time for me without Ruud even testing it (Yes, he’s that good!). You are basically using PHP to accomplish this and Lines 1 & 4 open and close the php statement Textpattern style.
Line 2 is an array that you can place your form names in, as many as you would like, and Line 3 randomly picks one and outputs it for you using the output form PHP hook in Textpattern. Now all you need to do is wrap this in the
txp:if_individual_article tags and put it at the bottom of your default article form. Done. Thanks Ruud!
Need more help with Textpattern?
If you are still stuck and need more help with Textpattern then I highly recommend the following book that was written by the Textpattern and Plugin Developers.
- Textpattern Solutions: PHP-Based Content Management Made Easy Friends of Ed, 2007