【问题标题】:Transofrm sql query to wordpress query with new wp_query使用新的 wp_query 将 sql 查询转换为 wordpress 查询
【发布时间】:2015-04-23 10:13:08
【问题描述】:

我正在尝试将 sql 查询转换为 wordpress 查询,但无法理解它是如何完成的?

我尝试转换为new wp_query的查询

$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);

所以我可以使用

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

喜欢

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

【问题讨论】:

    标签: php mysql sql-server wordpress


    【解决方案1】:

    试试:

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

    或使用标准的 WP_Query 函数:

    $wpq = new WP_Query($query);
    

    【讨论】:

    • 在 sql 上没有出现和测试,应该出现
    • 像这样添加:$topics = new WP_Query(); $topics->parse_query($query); 之后 while abd 不起作用。
    • 我更新了答案。我应该注意到你需要让你的帖子这样做。重新阅读您的问题,我认为您可能想要第二种格式。
    • 不知道新的qp查询可以处理sql。
    • -1 我不小心投了赞成票,因为它看起来像是在工作。但事实证明并非如此。像这样初始化 WP_Query 将根据默认设置返回所有帖子类型,但似乎不会考虑传递的 SQL 查询。
    【解决方案2】:

    我尝试了 bobdye 的解决方案,但事实证明它不起作用。据我所知,设置循环并使用the_title()$post->ID 等的唯一方法是这样工作:

    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();
    }
    

    这个问题是分页。但我相信这个答案可以巧妙地解决它: https://wordpress.stackexchange.com/questions/21626/pagination-with-custom-sql-query#28717

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 2015-10-10
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多