Textpattern tips, tutorials and code snippets

Rewrite individual article URL to the section page

In the new IMCA site I had a section with one article which I wanted to appear in search but I also did not want it to appear in its normal url but on the landing page of the section.

The problem is with the search results where the articles appear with their urls. What I had to do is to rewrite their individual urls to the section ones.

A big thanks goes to Robert (wet) who came up with a solution for my problem (the code below).

The code I use

<txp:if_article_section name="about">
 <txp:php>
  txp_status_header('301 Moved Permanently');
  header('Location: http://mysite.tld/about/');
  exit;
 </txp:php>
</txp:if_article_section>

How it works

The if_article_section tag is very handy when checking if the article in question matches a named section. From Textpattern Docs:

The tag will execute the contained statements if the section name associated with a particular article matches the value of the name attribute.

So, if the user visits the article URL then he or she will be redirected to the section page and the URL will be rewritten.

Check out the result

To see this in action, visit this link – check the url of the article returned in the search results and then click on it and look at the page url.

If you use this code, don’t forget to edit header('Location: http://mysite.tld/about/'); to match your chosen URL.

3 Comments Comment feed

  • AlanW
  • 26 January 2011

I understand the need, and it exposes a weakness in Textpattern’s search, but I’m not sure of the implications of 301-ing a page that actually has value (seems contradictory.) Could you use a search results form to rewrite the url?

<txp:if_article_section name="about">
<txp:section name="about"><txp:title /></txp:section>
<txp:else />
<txp:whatever />
</txp:if_article_section>

You could then canonicalize the url:

<link rel="canonical" href="<txp:site_url /><txp:section />" />

And add to preserve any links.:

<link rel="noindex,noarchive,follow" />
  • AlanW
  • 5 April 2011

Sorry,

“And add to preserve any links:”

Should have been:

<meta name="robots" content="noindex,noarchive,follow" />

Hi Alan,

Your method is indeed much better. By adding the code below in the search_results form the links direct straight to the section pages.

<txp:if_article_section name="section_name_1,section_name_2,etc">
<h3 class="entry-title"><a href="<txp:site_url /><txp:section />/"><txp:section title="1" /></a></h3>
<p class="entry-summary"><txp:search_result_excerpt /></p>

<p class="small"><a href="<txp:site_url /><txp:section />/"><txp:site_url /><txp:section />/</a></p>

<txp:else />
<h3 class="entry-title"><txp:permlink><txp:title /></txp:permlink></h3>

<p class="entry-summary"><txp:search_result_excerpt /></p>

<p class="small"><txp:permlink><txp:permlink /></txp:permlink></p>
</txp:if_article_section>

Add a comment

Use Textile help to style your comments