简体   繁体   English

在Wordpress中使用array_merge后,限制每页的帖子数

[英]Limit posts per page after using array_merge in Wordpress

I have two post types I want to display, Posts and then a Custom Post Type called 'Notes'. 我要显示两种帖子类型:“帖子”,然后是一个名为“注释”的自定义帖子类型。 I want to query both of these and display them together. 我想查询这两个并将它们一起显示。 I've currently got it working using array_merge. 我目前使用array_merge使它正常工作。

I want to create a new query so I can choose how many posts to display per page and also get pagination working. 我想创建一个新查询,以便可以选择每页显示多少帖子,并使分页正常工作。 I've tried various different things to limit the amount of posts displayed but can't seem to crack it. 我尝试了各种不同的方法来限制显示的帖子数量,但似乎无法破解。

Here is my code: 这是我的代码:

$q1_args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'post_status' => 'publish'
);
$q1_posts = get_posts( $q1_args );

// get the posts for the second query
$q2_args = array(
    'post_type' => 'notes',
    'posts_per_page' => -1,
    'post_status' => 'publish'
);
$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 ) {
    $post_type = $post->post_type;
    setup_postdata( $post );

    //DO STUFF
}

Any thoughts on how I can limit posts per page and get pagination working? 关于如何限制每页帖子数和使页面分页有效的想法?

Is there any particular reason this can't be done like this? 有什么特别的原因不能像这样吗?

$args=array(
    'post_type' => array('post', 'notes'),
    'posts_per_page' => 15, //or any other number you want per page
    'post_status' => 'publish',
    'orderby' => 'date',
    'order' => 'DESC',
    'paged' => (( get_query_var('page') ) ? get_query_var('page') : 1)
);
$posts=get_posts($args);
if ($posts->have_posts())
{
    while ($posts->have_posts())
    {
        $posts->the_post();
        //DO STUFF
    }
    //add pagination here
}
else
{
    // no posts found
}
wp_reset_postdata();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM