Textpattern tips, tutorials and code snippets

Search with Textpattern

Textpattern features in-built search functionality, which makes it very simple to display a search box for your users as well as customising the output of the search results.

Create a search form

<h2>Site search</h2>
<txp:search_input label="" button="Go" size="15" wraptag="p" />

Copy the above code and create a new form called search and save as type misc.

Call the search form in your page template

Where you would like to display your search form, place this: <txp:output_form form="search" />.

Customise the search results on your default page

<txp:if_search>
<txp:article limit="10" pgonly="1" />
<txp:if_search_results>
<h2><txp:search_result_count text="" /> articles match your search request "<txp:search_term />":</h2>
<txp:else />
<h2>Sorry, we were not able to find an article matching your search request "<txp:search_term />".</h2>
<p>Please try another search term, or browse the site to find what you are looking for.</p>
</txp:if_search_results>
<txp:article limit="10" sort="posted desc" />
<txp:ob1_pagination firsttext="First page" previoustext="Previous page" nexttext="Next page" lasttext="Last page" ulclass="pagination" liselected="active" />
<txp:else />
<txp:article form="article_list" limit="10" />
<txp:ob1_pagination firsttext="First page" previoustext="Previous page" nexttext="Next page" lasttext="Last page" ulclass="pagination" liselected="active" />
</txp:if_search>

By default, any search results will be parsed by the default section. You can of course change this. Let’s go through the code step by step:

  1. The <txp:if_search> is a conditional tag that checks if we are on a page as a result of a search
  2. <txp:article limit="10" pgonly="1" /> counts the number of search results
  3. <txp:search_result_count text="" /> setting the attribute text=”“ stops the default text “articles found” from displaying
  4. The limit=“10” in <txp:article limit="10" sort="posted desc" /> – which displays the actual results – should match the limit number set in <txp:article limit="10" pgonly="1" />
  5. We use the ob1_pagination plugin for our search results, but you can also use the in-built TXP pagination tags txp:older and txp:newer
  6. Since we are using the default page in our example, we use the <txp:else /> statement to display non-search articles if we are not in a search page

Taking it further

You may also use a different section for your search results if you wish to keep your default page for other purposes.

1 Comment Comment feed

but how i can stylize my search results with search result tags, like a:

<div class=“search_blocks”>
<div class=“search_block”>
<div class=“search_topic”><txp:search_result_title /></div>
<div><txp:search_result_excerpt /></div>
<div class=“search_link”><txp:search_result_url /></div>
</div>

Add a comment

Use Textile help to style your comments