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

I'm trying to modify how results are displayed in a post list that's currently controlled by the code below. However, it's not built in the WP_Query while ( $the_query->have_posts() ) : $the_query->the_post(); style I'm accustomed to and have built a lot of shortcodes and loop styles around.

How can I change the code below into a "regular" Wordpress loop that will allow me to use template tags like the_title()?

    $totalposts = $wpdb->get_results($querystr, OBJECT);
    $wp_query->request = $querystr . " LIMIT " . $ppp . " OFFSET " .$offset;
    $results = $wpdb->get_results($wp_query->request, OBJECT);
    foreach ($results as $result) {
        $output .= '<a href="'.get_post_permalink($result->ID).'">' . $result->post_title . ' (' . $result->post_date . ')</a><br>';
share|improve this question
What are the query params? – Cristian Jul 15 '11 at 19:54
this really depends on whats in $querystr – Bainternet Jul 15 '11 at 22:15

How I have done custom queries in the past is use $wpdb->get_col() and just returned an array of IDs of the posts. Then I pass that to a get_posts() passing the IDs to the post__in parameter. That way you can then use WP standard controls.

share|improve this answer
up vote 1 down vote accepted

In order to be able to use template tags, you have to do two things after getting your custom select query:

  1. You have to declare the global $post variable.
  2. You have to call the setup_postdata($post) function to populate the variables.

So, my code had to be changed like so:

$results = $wpdb->get_results($wp_query->request, OBJECT);
global $post;
foreach ($results as $post) {
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>


The key to this is on this codex page:

Displaying posts using a custom select 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.