简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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