In a plugin, I want to provide a function for users to set the default query in their templates, so they can use some custom loops. What would be the best way of doing it?

I imagine something like this:

if ( have_posts() ) {
    while ( have_posts() ) {
        ... iteration through a predefined post set ...

2 Answers 2


If you want to plug into the query, pre_get_posts() is going to be your friend. Pippin Williamson also has a great writeup on the subject.

  • Actually, @Zach, I wanted something to be done in some template parts when the theme developer wants to. See the edit. Sep 11, 2012 at 19:56

I did this, and it's working, but I'm not sure if it's the best way of doing it:

function get_override_query() {
    $posts = get_posts_from_some_custom_method();
    $query = new WP_Query();
    $query->current_post = -1;
    $query->post_count = count( $posts );
    $query->posts = $posts;        
    return $query;

function override_query() {
    global $wp_query;
    $query = get_override_query();
    $wp_query = $query;

Then, I can also iterate through posts without changing the default query, like:

$query = get_override_query();
while ( $query->has_posts() ) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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