filters - Add posts to WP Query object

admin2025-01-07  4

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?

Share Improve this question asked Nov 16, 2014 at 21:10 user1049961user1049961 4552 gold badges8 silver badges22 bronze badges 2
  • 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 Commented 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 – Pieter Goosen Commented Nov 17, 2014 at 6:55
Add a comment  | 

2 Answers 2

Reset to default 0

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' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736261789a769.html

最新回复(0)