Query Builder
Lumberjack has a built-in query builder which provides an expressive, fluent and explicit way of querying data in WordPress. It can be used instead of WP_Query to query posts (of any type) and means you do not have to worry about "the loop".
There are 2 ways in which you can use the query builder. Either on a Post Type:
Or by using the query builder directly:
Using the query builder on a Post Type
This is the most common way to use the query builder. You can start querying posts simply by using the Rareloop\Lumberjack\Post
class. To start a query, use the builder()
method.
This creates an instance of Rareloop\Lumberjack\ScopedQueryBuilder
. This class does a couple of important things:
Returns the correct post objects
When querying a post type, you will always get the same post object back in your results rather than WP_Post
objects.
For example, if you have a custom post type called Employee
, when you query employees you will always get Employee
objects back as results. Lets see what this looks like:
The collection contains instances of the Employee
class. This is extremely powerful as you now have access to all the behaviours that come with employees, as defined in your post type class. In this case, you may have a photoUrl()
method on an Employee
that knows (encapsulates) how to get the correct size image from the featured image:
And when iterating through your results, you can safely use this photoUrl()
method:
All post types extend Timber's Post object, so you get access to all of their behaviour out of the box.
The example above is making use of Timber's thumbnail()
method on a Post, and src()
method on an Image.
If collections are new to you, be sure the check out the documentation on them:
Query scopes
Sometimes you will need to perform the same filter on a query in multiple places within your theme.
In this example, we are scoping the query to only show featured images. However there's 2 issues with this:
We doing it twice, without reusing any code
It can be unclear as to what you are doing
Instead, We can encapsulate the knowledge about how to find featured posts by creating a query scope on our post type:
Now we have a query scope, we can refactor our previous queries, making them more declarative and easier to change:
Query scopes must start with the word scope
, and must follow with the name of the method you want available to the builder. The method should also be defined in CamelCase
. For example:
scopeFoo()
will allow you to call foo()
on a query.
scopeFooBar()
will allow you to call fooBar()
on a query.
You can also pass through parameters into the query scope:
Available methods
All the available methods can be chained, with the exclusion of getParameters
and get
.
getParameters
returns: array
Get the current state of the query builder, as an array. These parameters can be directly fed into WP_Query as arguments.
For example:
This can be useful if you need to add your own arguments that the query builder does not support.
Alternatively, you can add your own methods to the query builder using macros. See Extending the Query Builder.
wherePostType($postType)
$postType
string
| array
e.g. 'post', 'page'
Scope the query to a particular post type, or post types.
Populates post_type
in WP_Query
.
When using the query builder from a post type, the query is automatically scoped to the correct post type.
Reference: WP_Query - Type Parameters__
whereIdIn(array $ids)
$ids
array
An array of post IDs
Scope the query to only look for specific post IDs.
Sets the post__in
argument in WP_Query
.
Reference: WP_Query - Post & Page Parameters__
whereIdNotIn(array $ids)
$ids
array
An array of post IDs
Scope the query to exclude specific post IDs.
Sets the post__not_in
argument in WP_Query
.
Reference: WP_Query - Post & Page Parameters__
whereStatus()
This method can either take an array of statuses, or multiple parameters for each status:
Array of statuses:
$statuses
array
An array of statuses. e.g. publish
or draft
Multiple parameters:
$status
string
A status. e.g. publish
or draft
$status
string
A status. e.g. publish
or draft
...
...
...
Scope the query to only include posts with the given status. By default WordPress will only look for published posts, so you only need to use this method if you need to get posts with other statuses.
Sets the post_status
argument in WP_Query
.
Reference: WP_Query - Status Parameters__
whereMeta($key, $value, $compare = '=', $type = null)
$key
string
The meta key
$value
string
The meta value
$compare
string
Optional. Defaults to =
$type
string
| null
Optional. Defaults to null
. Pass in a value here to define the custom field type. e.g. numeric
.
Scope posts that have the specified custom meta fields.
Adds an array of meta query arguments to the array of meta_query
arguments on WP_Query
.
Note: meta_query
takes an array of meta query arguments arrays (it takes an array of arrays)
The above example can be written like so:
You can also add multiple meta queries.
This will yield the following parameters:
Reference: WP_Query - Custom Field Parameters__
whereMetaRelationshipIs(string $relation)
$relation
string
The type of relationship between meta queries.
Accepts and
& or
Sets the `relation` field for your meta queries, for `WP_Query`.
This will yield the following parameters, adding the 'relation' => 'or'
to the meta query.
Reference: WP_Query - Custom Field Parameters__
limit($limit)
$limit
int
e.g. 25
Set the number of results to get back from the query.
Sets the posts_per_page
argument in WP_Query
.
Reference: WP_Query - Pagination Parameters__
offset($offset)
$offset
int
e.g. 50
Set the number of results to displace or pass over.
Sets the offset
argument in WP_Query
.
Reference: WP_Query - Pagination Parameters__
orderBy($orderBy, $order = 'asc')
$orderBy
string
e.g. 'menu_order'
$order
string
Optional. Defaults to 'asc' (ascending)
Sort retrieved posts by parameter, e.g. date, title, menu_order.
Sets the orderby
and order
arguments in WP_Query
.
Reference: WP_Query - Order & Orderby Parameters__
orderByMeta($metaKey, $order = 'asc', $type = null)
$metaKey
string
The meta key to order by
$order
string
Optional. Defaults to 'asc' (ascending)
$type
string
Optional. Defaults to null.
Sorting will be alphabetical for strings. When dealing with numbers, you can get some unexpected results (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect).
Pass in 'numeric' here if you plan on sorting numbers.
Sets the `orderby` argument for `WP_Query` to `meta_value` when ordering strings, and `meta_value_num` when ordering numbers.
Reference: WP_Query - Order & Orderby Parameters__
as($postClass)
$postClass
string
The name of the post class that you want the results transformed to
When using WP_Query
, you get an array of WP_Post
objects back. The query builder will instead return an array of Rareloop\Lumberjack\Post
objects back.
You can use this method to change what object is returned from the query builder.
Note: When using the query builder on a post type, this conversion is done automatically. For example:
Reference: Timber - get_posts()__
get()
Execute the query and return a Collection
of post objects.
first()
Execute the query and return the first post object. Returns null
if there are no results.
clone()
Duplicates a new instance of the query builder with all the current parameters. You can modify this query builder instance separately to the original.
This can be useful if you have similar queries with subtle differences, as it saves you duplicating the commonalities between them.
Extending the query builder
The Lumberjack QueryBuilder
class can be extended with custom functionality at runtime (the class is "macroable"). The following example adds a search
method to the QueryBuilder
class that can be used to filter results based on a keyword search:
Last updated