Textpattern tips, tutorials and code snippets

Randomise anything

I recently wanted to present some videos hosted on vimeo in my site. vimeo allows us to create albums which are basically a collection of videos presented in a custom player. The problem is that albums do not play in mobile devices. As there were over 30 videos in total, loading them all individually would be too much for some devices. We also didn’t want to artificially prioritise any videos, so I was looking for a way to randomly load that content.

The solution was simple: linklist with the sort="rand()" attribute to the rescue.

In the link description field add the number of the video as generated by vimeo.

<txp:linklist category="my_link_list_video_category" limit="4" sort="rand()" wraptag="">
    <iframe src="http://player.vimeo.com/video/<txp:link_description escape="" />?title=0&amp;byline=0&amp;portrait=0" width="229" height="172" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</txp:linklist>

The code above could be adapted to randomise anything. For example to show some random quotes using the HTML5 standard, the code could become:

<txp:linklist category="my_link_list_quotes_category" limit="1" sort="rand()" wraptag="" />
<txp:variable name="linkurl" value='<txp:link_url />' />
<txp:if_variable name="linkurl" value="">
    <blockquote><txp:link_description escape="" />
        <cite><txp:link_title /></cite>
    </blockquote>
<txp:else />
    <blockquote cite="<txp:variable name="linkurl" />"><txp:link_description escape="" />
        <footer><a href="<txp:variable name="linkurl" />" rel="external"><txp:link_title /></footer>
    </blockquote>
</txp:if_variable>
</txp:linklist>

Read more about the linklist tag in the docs.