0
votes

What I have setup,

  1. A WordPress page with a permalink of /first/second
  2. A public Custom Post Type with a custom rewrite of /first/second

My goal is, To manage the content of the Custom Post Type archive via the WordPress page. I also need the posts of the CPT to have the same url structure, hence the rewrite.

So, /first/second will show the Post Type Archive /first/second/post-name will show a singular post from the CPT

This all works, but

My issue is, /first/second/page/2 throws a 404. I cannot for the life of me get the pagination to work on the custom post type feed. I'm sure it is because of a conflict with the rewrites since I have a CPT using the rewrite and a page.

I've tried overwriting the the query via pre_get_posts, but that physically updates the url as well, which is not what I want. I've also flushed the permalinks multiple times, so no dice there.

Any ideas? Some code...

add_action( 'init', 'rw_register_some_cpt' );

function rw_register_some_cpt() {

    $labels = array(
        'name'                  => _x( 'Some CPT', 'Post Type General Name', 'text_domain' ),
        'singular_name'         => _x( 'Some CPT', 'Post Type Singular Name', 'text_domain' )
    );

    $rewrite = array(
        'slug'                  => '/first/second',
        'with_front'            => false,
        'pages'                 => true,
        'feeds'                 => true
    );

    $args = array(
        'label'                 => __( 'Some CPT', 'text_domain' ),
        'description'           => __( 'Some CPT', 'text_domain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail', 'page-attributes' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'rewrite'               =>  $rewrite,
        'capability_type'       => 'page',
    );

    register_post_type( 'somecpt', $args );
}
1

1 Answers

1
votes

I had to write a custom rewrite rule to accomplish this. The issue was that Wordpress was assuming a /first/second/page/2 url was referencing a page with a permalink of /first/second/page, which did not exist. Attempting to overwrite the query with pre_get_posts did nothing either, as it caused WP to redirect to the non paged url.

So, by adding the following, it solved the pagination issue.

function rw_some_cpt_pagi_rewrite() {
  add_rewrite_rule('^first/second/page/([0-9]+)/?', 'index.php?page_id=50&paged=$matches[1]', 'top');
}

add_action('init', 'rw_some_cpt_pagi_rewrite');

Be sure to flush your rewrite rules.