Transofrm sql query to wordpress query with new wp_query

I am trying to convert an sql query to an wordpress query but fail to understand how is it done?

Query that I try to convert to new wp_query

Read More
$query = "  SELECT SQL_CALC_FOUND_ROWS distinct wp_posts.ID
            FROM   wp_posts
                   INNER JOIN wp_postmeta
                           ON ( wp_posts.id = wp_postmeta.post_id )
                   INNER JOIN wp_postmeta AS mt1
                           ON ( wp_posts.id = mt1.post_id )
            WHERE  1 = 1
                   AND wp_posts.id NOT IN ( 0 )
                   AND wp_posts.post_type = 'topic'
                   AND ( wp_posts.post_status = 'publish'
                          OR wp_posts.post_status = 'closed'
                          OR wp_posts.post_status = 'reported' )
                   AND ( wp_postmeta.meta_key = '_bbp_last_active_time')
            GROUP  BY wp_posts.id
            ORDER  BY wp_postmeta.meta_value DESC
            LIMIT  0, 10 
        ";
$topics = $wpdb->get_results($query, OBJECT);

so I can use

while($topics->have_posts()) : $topics->the_post(); ?>

smth like

$args = array(); // how do I convert to this.
$topics = new WP_query($args);

Related posts

Leave a Reply

2 comments

  1. Try:

    $wpq = new WP_Query();
    $wpq->parse_query($query);
    $posts = $wpq->get_posts();
    

    or to use the standard WP_Query functions:

    $wpq = new WP_Query($query);
    
  2. I tried bobdye’s solution, but it turns out it’s not working. The only way, as far as I know to set up a loop where you can go and use the the_title(), $post->ID and so on, is to work like this:

    global $post;
    
    $sql_results = $wpdb->get_results( $sql_query, OBJECT);
    
    if ($sql_results) {
        foreach ($sql_results as $post) {
          setup_postdata($post);
    
          // You're in the loop now. You can access all the $post objects
          // and functions like in any other wp loop.
          // example: the_title();
    
        }
      wp_reset_postdata();
    }
    

    A problem with this is pagination. But I believe this answer solves it neatly:
    https://wordpress.stackexchange.com/questions/21626/pagination-with-custom-sql-query#28717