Loading...
Skip to main content

WP_Query and pre_get_posts

Recently, a customer wanted to return a larger number of results on the taxonomy.php page. That page is returned when using taxonomies anyways, so, I had to look ‘before’ that was called.
The theme what was being configured was Bucket found here: BUCKET – A Digital Magazine Style WordPress Theme over at Themeforest.

The customer was displaying a certain number of results and wanted to show more, but did not know how to go about it. While looking at his custom taxonomy.php page, it was determined that the query was being set within the admin functions of the theme, and because of such, I needed to filter the query itself.

This is where pre_get_posts comes in handy. BUT, not to stop there, a couple more backward steps to the actual WP_Query itself.
CODEX describes both:

[box type=”shadow”]

WP_QUERY

WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a posts (or pages) request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it’s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.[/box]

[box type=”shadow”]

pre_get_posts

This hook is called after the query variable object is created, but before the actual query is run.
The pre_get_posts action gives developers access to the $query object by reference (any changes you make to $query are made directly to the original object – no return value is necessary).
[/box]

However, this special case only called for utilizing the existing $wp_query->query_vars[] and extrapolating a couple of them out: posts_per_page, orderby, and order. It went a little something like this:


function filter_posts_per_page_fs( $query ) {
    if ( !is_admin() && $query->is_main_query() && $query->query_vars['post_type'] !='post') {
           $query->set('posts_per_page', 50);
           $query->set('orderby','title');
           $query->set('order', 'ASC'); }
    return;
}

add_action('pre_get_posts','filter_posts_per_page_fs');

The customer was happy with the results after this little ditty was added to the child theme functions.php file.

No Comments yet!

Your Email address will not be published.


Shopping cart0
There are no products in the cart!
Continue shopping