Front end articles sorting

This tutorial allows users to sort articles with a select list and could help to solve this kind of request. It supports pagination and/or ajax loading.
It uses few customized rows of php from this tip by Jukka Svahn to set a cookie.

The code explained

An url variable named sort_by is used to set a cookie named sort_by_cookie. This cookie, if set, will contain the value of the variable and will continue to keep the sorting option in mind for you page after page, or load after load.

The code

<txp:variable name="custom_sorting"><txp:php>
	 * Checks if the HTTP GET or POST request
	 * contains 'sort_by' parameter. E.g.
	 * If it does, it proceeds to create a new cookie using
	 * PHP's setcookie() function. The cookie is named
	 * sort_by_cookie, contains the value of the 'sort_by' url variable
	 * and is set to expire in a year.
	 * The gps() function that is used to check the HTTP param
	 * existence is from Textpattern. The function can be used
	 * to return any HTTP POST or GET param by name.
	 * The PHP block outputs the value of the 'sort_by' url variable 
	 * using echo language construct.

	if (gps('sort_by'))
		setcookie('sort_by_cookie', $_GET['sort_by'], strtotime('+1 year'), '/');
		echo $_GET['sort_by'];

	 * If not doing the above 'sort_by', it
	 * checks if a cookie already exists.
	 * The check is done using Textpattern's cs() function.
	 * The function can be used to get any cookie from
	 * the HTTP request by name.
	 * Outputs the value of the cookie if true.

	else if (cs('sort_by_cookie'))
		echo $_COOKIE['sort_by_cookie'];

The above code that sets the variable would ideally be saved in a form, and then included on each page using output_form, e.g:

<txp:output_form form="sort_by_variable" />

Now, build your select list in a form or on your page:

<select onchange="window.location.href=this.value">
<option value="?sort_by=custom_1">Date</option>
<option value="?sort_by=custom_2">Date</option>

The following uses normal article and variable tags to check the above variable’s value and to sort articles. We use the values of the first and second custom fields to sort these articles.

<txp:article <txp:if_variable name="custom_sorting" value="custom_1">sort="(custom_1+0)"<txp:else /><txp:if_variable name="custom_sorting" value="custom_2">sort="(custom_2+0)"</txp:if_variable></txp:if_variable> />

Note: The above code has been tested locally but should be customized to fit your needs.

Further information on the forum. To find more information specifically about the few Textpattern functions mentioned above, search for gps() or cs() in the txplib_misc.php file: Textpattern code.

comments powered by Disqus