add_rewrite_endpoint() and Custom Post Type Archive

I’ve got a custom post type. Let’s call it books. I’m adding a new rewrite endpoint called pages.

I want the url /books/pages/2/ to work but I don’t see any rewrite rules generated by WordPress for this. I can manually add the rewrite rules for this specific example, but I’m looking for a way to make this work automatically.

How can I make this work automatically for any given custom post type archives? I’m guessing I’ll need to add a function to my plugin to look for all of the custom post types registered for the current site and then loop over that list adding the custom rewrite rules. Any better ideas?

Update
This is what I ended up doing:

function my_plugin_rewrite_rules( $wp_rewrite ) {
    $pages_regex = '?([\d\-]+|all)';

    $args = array(
        'has_archive' => true
    );
    $post_types = get_post_types( $args );

    $new_rewrites = array();
    foreach( $post_types as $post_type ) {
        $key = $post_type . '/pages/' . $pages_regex . '/?$';
        $val="post_type=" . $post_type . '&pages=" . $wp_rewrite->preg_index(1);

        $new_rewrites[ $key ] = $val;
    }

    $wp_rewrite->rules = $new_rewrites + $wp_rewrite->rules;
}
add_action("generate_rewrite_rules', 'my_plugin_rewrite_rules');

0

Leave a Comment