WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

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

This is similar to this question: How to change a custom query into a standard loop? - but I want to do this while writing a plugin, not writing a theme.

I need to be able to run a custom query (using regular old sql), and set the result as the post available for the loop. I am writing a plugin, so template tags, foreach loops, etc are not what I'm looking for. I just want to run my sql query, pick the correct row, and tell wordpress to use this as the post for the loop.

Here's what I've tried so far:

add_filter( 'pre_get_posts' , 'customQuery' );

function customQuery() {
  global $wpdb;
  $sql = "some sql here";
  $safequery = $wpdb->prepare($sql);

  $queryResults = $wpdb->get_results($safequery);

That works for retrieving my expected results. The variable $queryResults holds the correct data. After that line, I've tried a couple of things, neither of which worked.

global $post;
$post = $queryResults[0]; //since it is an array, and I just need the first result

That didn't work. Or rather, if I do a var_dump immediately after that line, $post is what I expect, but it seems to be reset somewhere down the line as I get a 404 when the page actually renders.

I also tried:

global $post;
$post = $queryResults[0];

Same outcome. If I check the values of variables right away, I see what I expect. With the second example I even tried, just for fun, running things like the_title(); which works (but doesn't help me because, again, I'm trying to write a plugin, not a theme). But when I let the page run through to rendering, I get a 404.

I'm sure I'm just missing something simple that'll let me pass my results to the loop from the plugin layer. Any suggestions? Thanks.

share|improve this question
up vote 0 down vote accepted

Found the correct hook to use. This intercepts the query and lets me modify it for my own purposes:

add_filter('posts_request', 'changeQuery');

function changeQuery($query) {
  $query = 'my new sql query here';
  return $query;
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.