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?

  • 2
    Out of curiosity, why do you need to do this? There may be better ways of doing this depending on what you're trying to achieve
    – Tom J Nowell
    Nov 16, 2014 at 22:25
  • 1
    Your question is just to vague to give a specific answer. There is just to much detail missing. To add to @TomJNowell comment, please provide an proper explanation to why you want to do this and what is your expected outcome, and also, what is the reason for the custom SQL query and not making use of WP_Query or get_posts. This might complicate things when merging your arrays. Please answer the requests in the form of an edit to your question. Thank you Nov 17, 2014 at 6:55

2 Answers 2


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):

Example from the WordPress Codex:

function exclude_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', '-1,-1347' );
add_action( 'pre_get_posts', 'exclude_category' );
  • 1
    I'm afraid I don't really see the relevance of your answer to the OP. The OP is about merging two queries Nov 17, 2014 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.