【问题标题】:Limit posts per page after using array_merge in Wordpress在 Wordpress 中使用 array_merge 后限制每页的帖子
【发布时间】:2016-03-04 15:16:02
【问题描述】:

我要显示两种帖子类型,帖子,然后是称为“笔记”的自定义帖子类型。我想查询这两个并将它们一起显示。我目前使用 array_merge 让它工作。

我想创建一个新查询,这样我就可以选择每页显示多少帖子并让分页正常工作。我尝试了各种不同的方法来限制显示的帖子数量,但似乎无法破解。

这是我的代码:

$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
}

关于如何限制每页帖子并让分页正常工作有什么想法吗?

【问题讨论】:

    标签: php wordpress loops foreach


    【解决方案1】:

    有什么特殊原因不能这样做吗?

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

    【讨论】:

    • 谢谢伊戈尔,我不知道我为什么要让它变得更复杂!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多