Applying a default sort sequence to the loops

It is possible to sort the output of loops using the {par} criteria. The template for the documentation you are currently reading has the same sorting criteria of {par num titre, titre} for all of its ARTICLES et RUBRIQUES loops.

Rather than repeat this in the code for all of the loops, we can apply it just once for all the loops if there is no other sorting criteria specified for a given loop. To do this, we use the pre_boucle pipeline and insert an ORDER BY for the SQL select queries.

Plugin.xml:

<pipeline>
	<nom>pre_boucle</nom>
	<inclure>documentation_pipelines.php</inclure>
</pipeline>

documentation_pipelines.php:

function documentation_pre_boucle($boucle){
	// ARTICLES, SECTIONS : {par num titre, titre}
	if (in_array($boucle->type_requete, array('rubriques','articles'))
	AND !$boucle->order) {
		$boucle->select[] = "0+" . $boucle->id_table . ".titre AS autonum";
		$boucle->order[]  = "'autonum'";
		$boucle->order[]  = "'" . $boucle->id_table . ".titre'";
	}
	return $boucle;
}

Doing this means that the loops are sorted by default:

// auto sort {par num titre, titre} :
<BOUCLE_a1(ARTICLES){id_rubrique}>...
// different sort:
<BOUCLE_a2(ARTICLES){id_rubrique}{!par date}>...

A few details

The pipeline receives a "boucle" (loop) type PHP object that may have various values. The loop notably has some select and order variables which handle what will be entered into the SELECT and ORDER BY clauses of the generated SQL query. The SQL table name (spip_articles or spip_rubriques in the current case) is stored in $boucle->id_table.

When we assign a number within the titles of SPIP articles (which do not have any ranking field in their tables even though the code has already been envisaged to handle it!), we write it like this: "10. Title" (number point space Title). In order for SQL to be able to easily sort by number, all that is needed is to force a numerical evaluation of the field (which is then converted into a number). This is why the code "0+titre AS autonum", which creates an alias column called autonum holding this numeric calculation value in it, is then able to be used as a sort column in the ORDER BY clause.

Author Mark Baber Published : Updated : 12/03/23

Translations : English, français, Nederlands