Contents
Most of the time when creating a new Swift Template, you’ll simply select what Custom Post Type to target and then build your Archive and Single Template.
However there are times when you’ll want to create a Custom Query that might:
- Order your Posts by Title or another field
- List only Posts with a particular tag
- Query based on a particular Author who wrote that post
Query Arguments
The Query Arguments interface allows you to quickly add some of the Query Arguments that are possible with WP_Query().
Query Arguments:
- Posts Per Page
- Order
- Order By
- Author ID
- Author nicename (not name)
- Category ID
- Category Slug
- Tag ID
- Tag Slug
- Post Parent ID
- Year
- Month
- Week
- Day
- Hour
- Minute
- Second
- Meta Key
- Meta Value
- Meta Value Numeric
- Meta Compare
To see accepted values just click the link “see accepted values” under the drop-down and a lightbox will appear with possible ( Query Arguments / Value ) combinations.
Custom Query Arguments
The above interface only supports the most common Query Arguments.
For things like Date Parameters, Taxonomy Parameters, Custom Fields Parameters (basically anything that isn’t available using the standard Query Arguments interface) you can download and install an add-on.
The add-on allows you to define any Query Arguments as a JSON with a structure similar to what WP_Query() accepts.
WCK Custom Query Arguments add-on
JSON Custom Query Examples
Taxonomy Select Argument
List Posts that have a particular term. Let’s say the Taxonomy name is genre and the term is comedy.
1 2 3 4 5 | {"tax_query":[{ "taxonomy":"genre", "field":"slug", "terms":["comedy"]} ]} |
Meta Query (Custom Fields)
Before querying after Posts with a particular Custom Field please note that by default WCK Custom Fields can not be queried because they are saved as a Serialized Array.
Now, in order to display Posts that have several Custom Fields you’ll do something like this:
1 2 3 4 5 6 7 | {"meta_query": { "relation":"OR", "0":{"key":"color","value":"blue","compare":"NOT LIKE"}, "1":{"key":"price","value":[20,100],"type":"numeric","compare":"BETWEEN"} } } |
To transform from an Array to JSON (since all examples about WP_Query() are using Arrays) you can use this online tool: Online json_encode.
Also, we’re requiring JSON instead of an Array due to security issues so we don’t execute arbitrary code.