query – Pagination not working on custom post types with rewrite slug

Question

I’ve been trying to fix my pagination to work on custom post type slugs for example article/post-title/page/2 it just keeps showing the first page’s results, the URL is changing but the posts remain the same

My post type has rewrite slugs written like this

'rewrite'       => ['slug' => 'article'],

This is the query I used
$paged = ( get_query_var(‘paged’) ) ? get_query_var(‘paged’) : 1;

    $args = [
        'numberposts' => -1,
        'post_type' => $post_type,
        'posts_per_page' => $post_per_page,
        'post_status' => 'publish',
        'paged' => $paged,
        'orderby' => [
            'date' => 'ASC'
        ]
    ];
return new \WP_Query($args);

This is the paginate link I used

$total_pages        = $query->max_num_pages;
    $current_page = max(1, get_query_var('paged'));

    return paginate_links(array(
        'base' => get_pagenum_link(1) . '%_%',
        'format' => 'page/%#%',
        'current' => $current_page,
        'total' => $total_pages,
        'prev_text'    => __('« prev'),
        'next_text'    => __('next »'),
    ));

It’s working on a normal page but on the post type it kept refreshing the page so I used these rewrite rules which now change the URL but it still shows the same results(cleared permalinks and all that too)

add_action('init', function() {

            add_rewrite_rule( "^article/([^/]+)/?", 'index.php?post_type=article&name=$matches[1]', 'top' );
            add_rewrite_rule( "([^/]+)/page/([0-9]{1,})/?$", 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top' );
            add_rewrite_rule("article/([^/]+)/page/?([2-9][0-9]*)",
                "index.php?post_type=article&author_name=\$matches[1]&paged=\$matches[2]", 'top');
            add_rewrite_rule("article/([^/]+)",
                "index.php?post_type=article&author_name=\$matches[1]", 'top');
    });

Tried different rewrite rules but nothing was working these were the latest ones I tried and the URL is changing with these but the results remain the same

0
Anup 4 months 2022-04-25T17:43:01-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse