问题描述

我正在将两个不同的帖子类型合并到一个循环中的网站上建立一个部分,然后随机显示它们。问题是,我很难找到一种方式来限制每个类型的帖子数量。

这是我试过的:

  • 具有多个 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 查询数据库,但是我需要能够将这两个单独的后期类型组合在一个循环中,随机布置,并限制为每种类型的一定量的帖子。

谢谢你的帮助!

最佳解决方案

一种方法是自定义使用 posts_clauses 或其他此类过滤器执行的 SQL 查询。为了找到它们,在”wp-includes/query.php”& C 中搜索 posts_clauses 看到这一行之前的一系列过滤器。这些一起可以自定义查询的任何部分

您可以做的另一件事是手动合并对象中查询的帖子

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

次佳解决方案

@mridual aggarwal 你的答案是非常好的,但不幸的是,并不是真正的组合 2 wp_query 它只显示从两个安排的帖子我的意思是从第一个& 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();?>

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。