Pagination in plugin with custom post type

the_posts_pagination uses global query and global query does not have pagination. So it is the correct behavior of WordPress.

To overcome from this problem assign custom query to global query then after looping again restore the global query.

function foo($args){
    $post_type = $args['post_type'];
    global $wp_query;
    $original_query = $wp_query;
    $custom_post_type = new WP_Query(
        array(
            'post_type' => $post_type,
            'orderby' => 'date',
            'order' => 'DESC',
            'posts_per_page' => 4
        )
    );

    $wp_query = $custom_post_type;

    if( $custom_post_type->have_posts() ) :
        while( $custom_post_type->have_posts() ): $custom_post_type->the_post(); ?>
            <h1><a href="https://wordpress.stackexchange.com/questions/216821/<?php the_permalink(); ?>"><?php the_title() ?></a></h1>
            <p> <?php the_modified_date(); echo ", "; the_modified_time() ?></p>
            <p> <?php the_excerpt() ?></p>
        <?php endwhile;
        the_posts_pagination();
    endif;
    wp_reset_postdata();

    $wp_query = $original_query;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)