pre_get_posts on a page

Explaining the object.

You don’t have to manually force data into those class properties. The whole $wp_query object has a bunch of internal methods that you should use to set values. Here’s an example:

public function query( $query )
{
    if (
        'SOME_POST_TYPE' !== $query->get( 'post_type' )
        OR ! $query->is_main_query()
        OR ! $query->is_archive()
        OR ! $query->is_post_type_archive()
        OR ! is_page_template( 'TEMPLATE_NAME.php' )
    )
        return $query;

    $query->set( 'posts_per_page', -1 );
    $query->set( 'numberposts', -1 );

    return $query;
}

Built in taxonomies: Categories & Tags

A Single term/category/taxon

If you want to query for categories and set them manually, then you have a pretty easy task, as you don’t have to to a tax_query:

$query->set( 'category__in', 13 );

Multiple terms/categories/taxons

If you need to query for multiple categories:

$query->set( 'category__and', array( 12, 13 ) );

You can read more about this on the Codex page for the WP_Query class. And of course you have the same possibilities for the built in post_tag/Tags taxonomy.

Custom taxonomies

Here things slightly get more complicated: You’ll need to use a tax_query. Keep in mind that this needs an array( array() ). In plain words: One surrounding array and inside this one another one. If you don’t do this, WP will fail silently. Example:

$tax_query = array(
    array(
         'taxonomy' => 'event_type_taxonomy'
        ,'field'    => 'id'
        ,'terms'    => array( 12, 13 )
        ,'operator' =>'IN'
    )
);
$query->set( 'tax_query', $tax_query );

Extended explanation again on the Codex page.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)