Automatic links

2018-03-31 18:00

Keywords: article, link, auto, title

Once again, the inspiration comes from Textpattern Forum:

Automatically read content from a custom field (or as well article body), process for terms, which have a respective article in database under same name, then link those terms automatically to the respective article, when displaying the content of the custom field (or article body), which contains it.

For example, suppose that we want to link every article title in the following article body:

Some text surrounding Apropos article title.
Some text surrounding etc_query article link.
Some text surrounding Tricky Problem article title.

Our solution will be based on this one, but is more title-targeted and exhibits some new txp 4.7 features.

Solution

A natural idea is to replace each encountered article title with the corresponding article link. To this end, we first create a JSON-encoded replacements array:

<txp:variable name="replacements">{
<txp:article_custom break=",">
	"<txp:title escape="json" />" : "<txp:permlink escape="json"><txp:title /></txp:permlink>"
</txp:article_custom>
}</txp:variable>

which produces (among other entries)

{
"Apropos" : "<a rel=\"bookmark\" href=\"https:\/\/iut-fbleau.fr\/projet\/etc\/index.php?id=2\">Apropos<\/a>",
"etc_query" : "<a rel=\"bookmark\" href=\"https:\/\/iut-fbleau.fr\/projet\/etc\/plugins\/etc_query\">etc_query<\/a>",
"Tricky Problem" : "<a rel=\"bookmark\" href=\"https:\/\/iut-fbleau.fr\/projet\/etc\/index.php?id=4\">Tricky Problem<\/a>"
}

Straightforward replacements would create links inside links, so we need to target precisely the concerned elements of the document. This will create links only in paragraphs text, but not inside other tags:

<txp:etc_query data='<txp:body />' 
	replace="//p/text()&={$json_decode({?replacements}|1).strtr({?}|$)}" />

Result

Some text surrounding Apropos article title.
Some text surrounding etc_query article link.
Some text surrounding Tricky Problem article title.

File(s)