Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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) {
        $offset++;
        $output .= '<a href="'.get_post_permalink($result->ID).'">' . $result->post_title . ' (' . $result->post_date . ')</a><br>';
    }
share|improve this question
1  
What are the query params? –  Cristian Jul 15 '11 at 19:54
1  
this really depends on whats in $querystr –  Bainternet Jul 15 '11 at 22:15

2 Answers 2

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) {
    setup_postdata($post); 
?>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>

etc.

The key to this is on this codex page:

Displaying posts using a custom select query

share|improve this answer

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

Your Answer

 
discard

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.