Search code examples
phpwordpresspermalinks

Remove Dash/Hyphen From Wordpress CustomPosttype Permalink


I want to remove all hyphens/dashes from the custom post type permalink in Wordpress.

For example:

www.website.com/customposttype/post-name/

Becomes :

www.website.com/customposttype/postname/

I want automatic solution for future and old posts.

Any advice on how to do this with any functions.

Thanks


Solution

  • You need to use to hook into WordPress's sanitize title hook.

    function no_dashes($title) {
        return str_replace('-', '', $title);
    }
    add_filter('sanitize_title', 'no_dashes' , 9999);
    

    It will remove the dashes from the URL. However it will work only when you save a post. That is for new posts it will work just fine. But for existing posts, you have to go and edit/hit update/save to make it happen.

    TODO: Also you need to have to check for Custom Post Type also, so it does not apply for all post types.

    UPDATE: I thought adding post_type check would be easier hence I added above TODO, but you are right looks like we do not have any data related to that on the filter hook I used.

    For that please use this code and see if it works:

    function no_dashes( $slug, $post_ID, $post_status, $post_type ) {
    
        if( $post_type == "page" ) {
            $slug = str_replace( '-', '', $slug);
        }
        return $slug;
    }
    add_filter( "wp_unique_post_slug", "no_dashes", 10, 4 );