Skip to main content
Timber

You are reading the documentation for Timber v2.x. Switch to the documentation for Timber v1.x.

Timber\​PostQuery

Query for a collection of WordPress posts.

This is the equivalent of using WP_Query in normal WordPress development.

PostQuery is used directly in Twig templates to iterate through post query results and retrieve meta information about them.

Overview #

This class extends ArrayObject
This class implements Timber\PostCollectionInterface, JsonSerializable

Properties #

NameTypeDescription
$found_postsintThe amount of posts found in the query.

Methods #

NameReturn TypeSummary/Returns
__construct()Query for a collection of WordPress posts.
pagination()\Timber\PaginationGet pagination for a post collection.

Returns: object

Class Methods #

__construct() #

Query for a collection of WordPress posts.

Refer to the official documentation for WP_Query for a list of all the arguments that can be used for the $query parameter.

__construct( \WP_Query $query )

NameTypeDescription
$query\WP_QueryThe WP_Query object to wrap.

PHP

// Get posts from default query.
global $wp_query;

$posts = Timber::get_posts( $wp_query );

// Using the WP_Query argument format.
$posts = Timber::get_posts( [
'post_type' => 'article',
'category_name' => 'sports',
] );

// Passing a WP_Query instance.
$posts = Timber::get_posts( new WP_Query( [ 'post_type' => 'any' ) );

pagination() #

Get pagination for a post collection.

Refer to the [Pagination Guide]({{< relref "../guides/pagination.md" >}}) for a detailed usage example.

Optionally could be used to get pagination with custom preferences.

pagination( array $prefs = [] )

Returns: \Timber\Pagination object

NameTypeDescription
$prefsarrayOptional. Custom preferences. Default array().

Twig

{% if posts.pagination.prev %}
<a href="{{ posts.pagination.prev.link }}">Prev</a>
{% endif %}

<ul class="pages">
{% for page in posts.pagination.pages %}
<li>
<a href="{{ page.link }}" class="{{ page.class }}">{{ page.title }}</a>
</li>
{% endfor %}
</ul>

{% if posts.pagination.next %}
<a href="{{ posts.pagination.next.link }}">Next</a>
{% endif %}