I want to replace the main query with my own custom query. The thing is I don’t want to go through the hassle of manual paging. I know there’s a filter posts_results
but I’m not sure how to use it exactly, I couldn’t find a bunch of info on it. It looks like pre_get_posts
is only altering the query instead of replacing it entirely. I tried to just dump my query into $posts
but then I lost paging. Is there a way around this?
I’m using $posts = wpdb->get_results($query);
to replace the main query with my own.
$query
is my custom SQL. I’m adding the snippet above right under get_header()
. I’m trying to edit the main query on my custom taxonomy page: taxonomy-mytax.php
.
The Situation
Currently my client has Manufacturers (Taxonomy) and Products (Taxonomy) then an actual Product (Custom Post Type). They requested to show Product posts (on the product category page – taxonomy-producttax.php
) in an order by their most favorable Manufacturer (taxonomy). So I added an extra field into the manufacturer taxonomy where they can set a number that declares an order. This number is saved into $wpdb->terms.term_group
. Now on the Product Category page I’m trying to replace the main query entirely with a brand new query that will get all the products and put them in order by a manufacturers term_group
. Both Product and Manufactuers (both taxonomies) have an order, and both are put into $wpdb->terms.term_gruop
which was troublesome. I created a custom query that works, and will show posts in manufacturers term_group
order . I just need to replace the main query on taxonomy-producttax.php
with my custom SQL query, but I didn’t want to get into manual paging I wanted to use anything WordPress has built in to help me.
2 Answers
You cannot replace the main query with the output of $wpdb
. The main query is a WP_Query
object. $wpdb
returns a simple array or object, but not a WP_Query
object.
Even if you could shove raw SQL into a query (something in the back of my head makes me think you can but I can’t swear to it) it is not advisable. Try var_dump($wp_query);
and you will see that there is a lot going on besides just a SQL query. For the object to work–including the pagination that you want– all of that other stuff has to be set correctly.
You do need to use pre_get_posts
and perhaps other query filters like posts_where
to alter the WP_Query
object, not replace it. Without knowing the details as @Milo and @ChipBennett have requested but you are hesitant to provide, it is not going to be possible to give you much more of an answer.