Search code examples
phpwordpresspostpagination

Current CPT pagination not working when changing number of posts per page


I have a custom post type built by a Wordpress theme. All users can view a list of their own CPT posts at user backend.

I Managed to change the number of posts per page for all user roles (not Administrator role) successfully, but the number of pages of an existing pagination displayed incorrectly.

Here are my codes

    // Change the number of custom post type posts per page - WORKING, but the calculation of number of pages is not correct
    function change_cpt_posts_per_page( $query ) {
        $main_user = wp_get_current_user();
        if( $main_user->roles[0] !== 'administrator' && $query->is_main_query() && is_post_type_archive('my_cpt') ) {
            $query->set( 'posts_per_page', '100' ); // Set number of posts per page
        }

    }
    add_action( 'pre_get_posts', 'change_cpt_posts_per_page' );

The codes work very well for changing number of posts per page, but the number of pages of the pagination remains the same as default which 145 pages shown by Pagination at the bottom of the page. Please check a screenshot attached below:

    https://imgur.com/a/xd7W4b1

How to automatically RE-calculate the number of pages of the existing Pagination when changes in the number of posts per page set above?

Very appreciate any support.

I have tried the followings to automatically update the total number of pages of the pagination:

    $the_query = new WP_Query( $args );
    $args = array('total' => $the_query->max_num_pages);

    // OR:
    global $wp_query;
    // $total = $wp_query->max_num_pages;
    the_posts_pagination( array('total' => $wp_query->max_num_pages));

They dont work. Any help is very appreciated.

Update: I found out that my WP theme uses default WP pagination in this file:

    wp-admin/includes/class-wp-list-table.php

Solution

  • FIXED:

    I use this hook: edit_{$post_type}_per_page to update both number of posts per page, and number of pages (calculated automatically by WP) of the Pagination:

        https://developer.wordpress.org/reference/hooks/option/
    

    Here are fully working codes:

        function change_cpt_posts_per_page ( $per_page ) {
            $per_page = 100;        // Set number of posts per page
            return $per_page;
        }
        add_filter( 'edit_{$post_type}_per_page', 'change_cpt_posts_per_page', 10, 1 );
    

    Thanks