Sam Brown

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:

  1. <txp:php>
  2. $forms = array('form1', 'form2', 'form3');
  3. echo output_form(array('form' => $forms[rand(0, count($forms)-1)]));
  4. </txp:php>
  5. 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.

Post a link to this on Twitter ↩


Brendan Cullen 25 January 2008, 15:06 #1

Nice! I was looking for something like this a while back. Thanks for sharing :)

Spencer 26 January 2008, 09:58 #2

Great, thanks for sharing this! Very helpful! I’m still a newbie to Textpattern, and still really feel like I don’t have a grasp on it yet. I did get the Textpattern Solutions book, and that has helped out a lot. Anyways, thanks again.

Sam Brown 28 January 2008, 03:35 #3

Hi Guys, glad it helps. I think this ability should be built in, but we will have to wait and see. 4.0.6 soon!

Viking KARWUR 28 January 2008, 20:11 #4

Hi Sam… Thanks for sharing…
I tested TXP 4.0.6 RC 1 right now :)

Commenting has closed for this article. Feel free to me.

Sam Brown co-founded Iterate, and was previously VP of Design at Foursquare. Based in NYC.