Change permalink structure for custom post type

Note one Important thing to the above answer:

While it’ll work fine from the first sight it will cause performance problems.
All this code will be called on init hook so every page load will cause it to run and flush_rules() is very time expensive.

So it’s recomended to call flush rules upon theme\plugin activation only. Also you can use add_permastruct functions without need to access global $wp_rewrite

Final improved solution would be:

add_action('init', 'my_custom_rewrite'); 
function my_custom_rewrite() {

    add_permastruct('hardware', '/%customname%/', false);
    add_permastruct('produkt', '/%customname%/', false);
}

add_filter( 'post_type_link', 'my_custom_permalinks', 10, 2 );
function my_custom_permalinks( $permalink, $post ) {
      return str_replace( '%customname%/', $post->post_name, $permalink );
}

 /* in case for plugin */
register_activation_hook(__FILE__,'my_custom_plugin_activate');
function my_custom_plugin_activate() {
    flush_rewrite_rules();
}


/* in case of custom Theme in Functions.php */
add_action('after_switch_theme', 'mytheme_setup');
function mytheme_setup () {
    flush_rewrite_rules();
}

Leave a Comment