我使用以下方法将多个查询组合为一个循环:
function order_by_date( $a, $b )
{
return strcmp( $b->post_date, $a->post_date );
}
// get the posts for the first query
$q1_args = array(
// args for the first query
);
$q1_posts = get_posts( $q1_args );
// get the posts for the second query
$q2_args = array(
// args for the second query
);
$q2_posts= get_posts( $q2_args );
// Merge the post arrays together, and sort by date using the order_by_date function
$final_posts = array_merge( $q1_posts, $q2_posts );
usort( $final_posts, \'order_by_date\' );
// Loop over the posts and use setup_postdata to format for template tag usage
foreach ( $final_posts as $key => $post ) {
setup_postdata( $post );
// Now we can use template tags as if this was in a normal WP loop
the_title(\'<h2>\',\'</h2>\');
the_content();
}
这很好,但当我尝试删除重复项时,我什么也没有得到(也没有错误):
// This is my code for trying to remove the duplicates
$final_posts = array_unique( array_merge( $q1_posts, $q2_posts ) );
对可能出现的问题有什么想法吗?
SO网友:Best Dev Tutorials
由于迈克尔的回答,我使用了另一种方法:
在循环之前,创建一个数组:
$do_not_duplicate = array(); // set an array for catching duplicates
然后在循环内部,将post id添加到数组中,如果它已经在数组中,则跳过它:
if (in_array($postID, $do_not_duplicate)) {
continue; // if its already been through it, dont display it
}
$do_not_duplicate[] = $postID; // add the id to the array