Get started with custom fields

An oft-overlooked part of Textpattern is its in-built custom field support.

Custom fields allow you to publish content that has a consistent structure across your site, for example an “author name”.

You can see an example of custom fields to the right of this text – in a box titled About this TXP Tip. The contents of that box are set in custom fields as defined below.

Name your custom fields

  1. Visit the Preferences > Advanced tab
  2. You will see ten custom fields, two are named custom1 and custom2 by default
  3. Change the name of the custom fields to suit your needs, in our case we used Author, Author_email and Author_URL

Once you have named your custom fields, visit the Content > Write tab and open the Advanced Options on the left. You will see the custom fields with the names you created earlier.

Display the custom fields in your page template

Either create a form for the custom fields code, or place it directly in your page template. We use a form called sidebar_tips and then call the form in the page using output_form.

<div class="box">
<h2>About this TXP Tip</h2>
<p>
<span class="bold">Posted by: </span> <txp:custom_field name="Author" /><br />
<span class="bold">Author email: </span> <txp:custom_field name="Author_email" /><br />
<span class="bold">Author URL: </span> <a href="http://<txp:custom_field name="Author_URL" />"><txp:custom_field name="Author_URL" /></a><br />
<span class="bold">Date: </span> <txp:posted />
</p>
</div>

The above is a nice first attempt – it will display the content of the three custom fields. But what if we don’t have any content in one or more of the content fields? Enter the wonderful if_custom_field conditional tag, which checks if the custom field has any content. If not, nothing displays :-)

<div class="box">
<h2>About this TXP Tip</h2>
<p>
<txp:if_custom_field name="Author"><span class="bold">Posted by: </span> <txp:custom_field name="Author" /><br /></txp:if_custom_field>
<txp:if_custom_field name="Author_email"><span class="bold">Author email: </span> <txp:custom_field name="Author_email" /><br /></txp:if_custom_field>
<txp:if_custom_field name="Author_URL"><span class="bold">Author URL: </span> <a href="http://<txp:custom_field name="Author_URL" />"><txp:custom_field name="Author_URL" /></a><br /></txp:if_custom_field>
<span class="bold">Date: </span> <txp:posted />
</p>
</div>

And that’s all there is to it ;-)

comments powered by Disqus