douchun6108 2016-03-04 15:16
浏览 62
已采纳

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

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.

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?

  • 写回答

1条回答 默认 最新

  • donglu1472 2016-03-04 15:57
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集