Use SQL-querys in the loop – WITH template tags
2010-01-16 @ 14:35The problem
I want to use SQL-querys within the WordPress loop and still be able to use the template tags. In this example I want both posts and pages within the loop. How can I do that? In both query_posts and WP Query I can only get specific posts OR pages, not both.
I’ve been searching the web for a way to combine multiple WP Query objects somehow, because I only want one loop.
The solution
The solution is by not using WP Query at all. This is how it works:
- Write a SQL Query. This gives you a great freedom to just select the post / pages you need, or a combination of them.
- Create a result object by using the function get_results.
- If I get a result, loop it out in a foreach loop.
- Use the function setup_postdata to be able to use WordPress template tags.
<?php
$query_sql = "
SELECT *
FROM $wpdb->posts
WHERE post_type = 'post'
OR post_type='page'
ORDER BY post_title DESC
";
$query_result = $wpdb->get_results($query_sql, OBJECT);
?>
<?php if ($query_result): ?>
<?php foreach ($query_result as $post): ?>
<?php setup_postdata($post); ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php endforeach; ?>
<?php else : ?>
<p>Not found</p>
<?php endif; ?>






2009-12-21 @ 2:46 e m
Found this while looking for a way to do exactly what you defined as the problem, having both posts and pages in one loop. I really wanted to find a way to combine two different queries into one result set, but this works almost as well – thanks a lot!