Textpattern tips, tutorials and code snippets

Related articles with custom fields

Editor note: An update to this article is available here: Custom article groups in textpattern.

Txp’s native related_articles tag relates articles by category. This works well for many uses, but sometimes you want finer control. related_articles either looks at both categories assigned to an article, which can be too broad, or only one, which can be too narrow. It also looks only for exact category matches and does not look further up or down the category tree (the chh_related_articles plugin can do so, however).

Say you have groups of articles about each year’s Wimbledon Championships going back several years. All of these articles are closely related and will almost certainly use the same categories, and yet you probably don’t want articles from 2007 showing up on the related articles list for an article about the 2009 tournament, and vice versa.

A expedient solution for some cases is to use a custom field to “hard-code” related articles. Not exactly “best practice” content management, and it would get out of hand quickly for a large group of articles, because of the need to update every article in the group when adding a new article, exactly the sort of thing a CMS is supposed to avoid. But it is a manageable solution for small groups of articles where categories and related_articles don’t produce the desired results.

Following is an example of how I’ve set this up.

Name a custom field “Related”

To assign related articles, enter a comma-separated list of article IDs into that field.

Add some code to the relevant article form

<txp:if_custom_field name="related">
<txp:article_custom id='<txp:custom_field name="related" />' break="li" wraptag="ul">
<cite><txp:permlink><txp:title /></txp:permlink></cite>
</txp:article_custom>
</txp:if_custom_field>

Of course you don’t have to use all the attributes and tags I’ve listed; the main points are to set the id attribute of the article_custom tag to the contents of the custom field, and to wrap it in an if_custom_field container.

Note that the order you list the IDs in your custom field will not be preserved in the list produced by the article_custom tag; it will default to Posted desc. If you need to preserve the listed order, there is a MySQL-specific variation you can use (note the sort attribute of the article_custom tag):

<txp:if_custom_field name="related">
<txp:article_custom id='<txp:custom_field name="related" />' sort='field(<txp:custom_field name="related" />)' break="li" wraptag="ul">
<cite><txp:permlink><txp:title /></txp:permlink></cite>
</txp:article_custom>
</txp:if_custom_field>

See this Txp support forum thread for more discussion.

Use Textile help to style your comments