Query Loops

Sorting

Sorting tells a query loop which WordPress order to use before TemplateX repeats the result markup.

Smallest Example#

Use sort="field:direction" on the query tag:

php
{{ query:posts sort="date:desc" }}  <h2>{{ title }}</h2>{{ /query:posts }}

date:desc shows the newest posts first. Use date:asc for oldest first.

Manual Order#

Use order:asc when editors arrange pages or post types manually in the WordPress admin:

php
{{ query:pages sort="order:asc" }}  <h2>{{ title }}</h2>{{ /query:pages }}

order is the TemplateX sort name for WordPress menu_order. Use order:asc for first-to-last manual order and order:desc for the reverse.

Do not write menu_order:asc in TemplateX templates. menu_order is the WordPress field name; TemplateX syntax uses order.

Alphabetical#

Use title:asc for A to Z:

php
{{ query:posts sort="title:asc" }}  <h2>{{ title }}</h2>{{ /query:posts }}

Use title:desc for Z to A.

Random#

Use random when the query should shuffle results:

php
{{ query:posts sort="random" }}  <h2>{{ title }}</h2>{{ /query:posts }}

Random sorting is useful for featured links, related posts, or rotating highlights.

Multiple Sorts#

Separate sort rules with | when one field should break ties for another:

php
{{ query:posts sort="order:asc|title:asc" }}  <h2>{{ title }}</h2>{{ /query:posts }}

TemplateX applies sort rules from left to right. In this example, WordPress uses manual order first, then title order for posts with the same manual position.

Sort Reference#

Sort valueWordPress orderUse for
date:descdate DESCNewest posts first.
date:ascdate ASCOldest posts first.
published:descdate DESCSame as date:desc.
modified:descmodified DESCRecently updated posts first.
title:asctitle ASCAlphabetical titles.
slug:ascname ASCPost slug order.
order:ascmenu_order ASCManual WordPress order.
order:descmenu_order DESCReverse manual WordPress order.
comment_count:desccomment_count DESCMost-commented posts first.
status:ascpost_status ASCGroup by post status.
randomrandRandom results.

If the field is not one of the names above, TemplateX treats it as a custom field key and sorts by WordPress meta_value:

php
{{ query:events sort="event_date:asc" }}  <h2>{{ title }}</h2>{{ /query:events }}

Custom field sorting uses WordPress text-style meta sorting. Store values in a sortable format, such as 2026-06-14 for dates.

Reader-Chosen Sorting#

Use search sorting when a reader should choose the order from the page:

php
{{ search }}  {{ sort }}    <option value="date:desc">Newest</option>    <option value="order:asc">Menu Order</option>    <option value="title:asc">Title A-Z</option>  {{ /sort }}{{ /search }}{{ query:posts search }}  <h2>{{ title }}</h2>{{ /query:posts }}

Search sort options use the same sort values as query loops. See Search Sorting for the form syntax.