[wp-hackers] Extending query_posts?

Mattias Winther mattias at winthernet.se
Sun Jan 29 11:12:10 GMT 2006

I am trying to learn how to write plug-ins, and at the moment I'm trying to create a "display random posts from a certain category"-plugin. I've tried Skippys version, and looked around for more, but I would like to have something that feels like less of a hack, and more of an extension, with correct usage of The Loop and so forth.

I've been thinking along two lines of how do achieve this. First off, the preferred way to do this would be to modify the query_posts results, but I'm thinking that doing that with the get_posts hook seems awfully unoptimized. So, in essence, I would like to first interpret the parameters sent to query_posts, then do my own search based on that, getting just post IDs, choose the required number of random posts, rewrite the entire query to just get the specific posts, and then relinquish control of the query.

The second way to do this, in my mind, would be to create a new query_posts function, that has similar syntax as the orginal one, and also gets a new iteration of The Loop going. the advantage with this approach would be that I can add parameters as I go along, with less possibility of rewriting queries the wrong way.

A few example queries might explain what I'm talking about, in the odd chance that I totally obfuscated it above:

<?php query_posts('category_name=special_cat&showposts=4&random=true'); ?>
<?php query_random_posts('category_name=special_cat&showposts=4'); ?>

Either of these should be followed with the standard:

<?php while (have_posts()) : the_post(); ?>
  <!-- Do special_cat stuff... -->
<?php endwhile;?>

or something along those lines.

Okay, description done. Now for the practicalities:

1. Are there any other approaches that might work better? I realize there are ways to do a hack that does this, but I really want to make it feel like it was integrated in the wordpress core.
2. Is there a hook for looking at and modifying the query just before sending it to the SQL server?
3. If not, how do I create a wp_query object from a query_random_posts function?

More information about the wp-hackers mailing list