Query both posts and pages within a loop

Taken from here: http://www.devdevote.com/cms/wordpress-hacks/use-sql-querys-in-the-loop-with-template-tags/

The 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:

  1. Write a SQL Query. This gives you a great freedom to just select the post / pages you need, or a combination of them.
  2. Create a result object by using the function get_results.
  3. If I get a result, loop it out in a foreach loop.
  4. Use the function setup_postdata to be able to use WordPress template tags.
$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; ?></pre>


There are no revisions for this post.

Tags: , ,

No comments yet.

Leave a Reply