Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

my_plugin_set_query();
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        ... iteration through a predefined post set ...
    }
}
share|improve this question

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.

share|improve this answer
    
Actually, @Zach, I wanted something to be done in some template parts when the theme developer wants to. See the edit. –  vmassuchetto Sep 11 '12 at 19:56
up vote 0 down vote accepted

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() ) {
    $query->the_post();
    ...
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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