Rewriting ‘rewrite’ slug for custom post type used by plugin

I searched everywhere in post type registration flow but didn’t found a right way (using filter or action) to do it.

All you can do either register the post type again with a different slug (I prefer) or just run those lines of code which WordPress run to build the rewrite rules in register_post_type.

I register this post type with slug book and changed it using this trick.
I am not sure it is 100% correct (as I am rewriting rules for the same post type) but it works.

add_action('registered_post_type', 'testbook', 10, 2);
function testbook($post_type, $args) {
    global $wp_rewrite;
    if ($post_type == 'book') {

        $args->rewrite['slug'] = 'changed_slug_book'; //write your new slug here

        if ( $args->has_archive ) {
                $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
                if ( $args->rewrite['with_front'] )
                        $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
                else
                        $archive_slug = $wp_rewrite->root . $archive_slug;

                add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
                if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
                        $feeds="(" . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
                        add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
                        add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
                }
                if ( $args->rewrite['pages'] )
                        add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
        }

        $permastruct_args = $args->rewrite;
        $permastruct_args['feed'] = $permastruct_args['feeds'];
        add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
    }
}

Leave a Comment