WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ...
share|improve this question

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() ) {
share|improve this answer

Your Answer


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.