我在一个网站上创建了一个部分,将两种不同的帖子类型合并到一个循环中,然后随机显示它们。问题是,我很难找到一种方法来限制每种类型的帖子数量。
以下是我尝试过的:
一个数组可以实现一个具有多种post类型的查询:
$args = array( \'post_type\' => array( \'photos\', \'quotes\' ), ...
。。。但不能限制每种类型的职位数量
运行前合并两个查询参数数组WP_Query 在其上:
$photos = array( \'post_type\' => \'photos\', \'posts_per_page\' => 15, \'orderby\' => \'rand\' );
$quotes = array( \'post_type\' => \'quotes\', \'posts_per_page\' => 5, \'orderby\' => \'rand\' );
$args = $photos + $quotes;
// Also tried array_merge( $photos, $quotes );
这方面运气不好。发生的是后一个变量
$quotes
覆盖
$photos
并且只显示引号
合并两个WP_Query 通过类型转换将对象组合在一起:
$photos_query = new WP_Query( $photos );
$quotes_query = new WP_Query( $quotes );
$result = (object)array_merge( (array)$photos_query, (array)$quotes_query );
。。。等等
我可能会直接使用SQL查询数据库,但我需要能够将这两种不同的帖子类型组合为一个循环,随机排列,并限制每种类型一定数量的帖子。
谢谢你的帮助!
最合适的回答,由SO网友:Mridul Aggarwal 整理而成
一种方法是使用自定义执行的SQL查询posts_clauses
或其他此类过滤器。要查找它们,请搜索posts_clauses
在“wp includes/query.php”中(&;请参见此行前面的过滤器系列。它们一起可以自定义查询的任何部分
您可以做的另一件事是在对象中手动合并查询的帖子
$photos_query = new WP_Query( $photos );
$quotes_query = new WP_Query( $quotes );
$result = new WP_Query();
// start putting the contents in the new object
$result->posts = array_merge( $photos_query->posts, $quotes_query->posts );
// here you might wanna apply some sort of sorting on $result->posts
// we also need to set post count correctly so as to enable the looping
$result->post_count = count( $result->posts );
SO网友:adnan
@MrIndual aggarwal你的答案很好,但不幸的是,它并没有真正结合2wp_query
它只显示了两个帖子的排列,我是指第一个和第二个帖子的5个帖子;第二个5个,但不是全部排序在一个中,因此我有此解决方案&;至少我自己也达到了目标
<?php
$term = get_term_by( \'slug\', get_query_var( \'tag\' ), "post_tag" );
$tagslug = $term->slug;
$post_types = get_post_types(\'\',\'names\');
?>
<?php
//first query
$blogposts = get_posts(array(
\'tag\' => $tagslug, //first taxonomy
\'post_type\' => $post_types,
\'post_status\' => \'publish\',
));
//second query
$authorposts = get_posts(array(
\'bookauthor\' => $tagslug, //second taxonomy
\'post_type\' => $post_types,
\'post_status\' => \'publish\',
));
$mergedposts = array_merge( $blogposts, $authorposts ); //combine queries
$postids = array();
foreach( $mergedposts as $item ) {
$postids[]=$item->ID; //create a new query only of the post ids
}
$uniqueposts = array_unique($postids); //remove duplicate post ids
$posts = get_posts(array(
//new query of only the unique post ids on the merged queries from above
\'post__in\' => $uniqueposts,
\'post_type\' => $post_types,
\'post_status\' => \'publish\',
));
foreach( $posts as $post ) :
setup_postdata($post);
?>
// posts layout
<?php endforeach; ?>
<?php wp_reset_postdata();?>