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.
...snip...
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:
...snip...
global $post;
$post = $queryResults[0];
setup_postdata($post);
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.