I need to filter the WP_Query object by adding some posts to it. I have the posts id's (from another SQL query). What would be the way to add (merge) new posts into the WP_Query object?
I need to filter the WP_Query object by adding some posts to it. I have the posts id's (from another SQL query). What would be the way to add (merge) new posts into the WP_Query object?
You should probably use the post__in argument of WP_Query, and pass in an array of post IDs. This will work assuming you run the query with the extra posts first. Injecting them into the WP_Query object like this allows SQL to still order the results, with the additional posts passed in.
If you're not writing the final query yourself (passing in your own array of arguments into WP_Query), then you'll have to use the pre_get_posts hook as mentioned in another answer. Although, make sure you do all the necessary checks to ensure that you don't affect the wrong query like this. You should still be able to set the post__in argument, but you'll have to do it in a different way.
If you just want to append some posts to the end some other list of posts, you can use some simple PHP operations. If you go with this route, the get_posts() function might be a good alternative to using WP_Query() if you just want to get an array of WP_Post objects, and not have to do all of this while( $query->have_posts() ) { the_post(); } garbage.
You can modify the query using the pre_get_posts hook, you will have to add the parameters of your query to the query provided by WordPress inside you callback function (exclude_category
in the example below):
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-1,-1347' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );
WP_Query
orget_posts
. This might complicate things when merging your arrays. Please answer the requests in the form of an edit to your question. Thank you – Pieter Goosen Commented Nov 17, 2014 at 6:55