0

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>';
    }
2
  • 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
1

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.