我正在尝试将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);
答案 0 :(得分:3)
尝试:
$wpq = new WP_Query();
$wpq->parse_query($query);
$posts = $wpq->get_posts();
或使用标准的WP_Query函数:
$wpq = new WP_Query($query);
答案 1 :(得分:0)
我尝试过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