permalink independent on the post’s name stored in the database

We have to do this keeping post_name unique. Otherwise, it might cause many troubles. We can use post_title with sanitize_title. In this way, you can keep your URL nice and clean, and your post_name will remain unique as well.

First we will need to write custom permalink structure.

function my_awesome_permalink( $url, $post, $leavename ) {
    $url= trailingslashit( home_url('/post/'. $post->ID ."https://wordpress.stackexchange.com/". sanitize_title($post->post_title) ."https://wordpress.stackexchange.com/" ) );
    return $url;
}
add_filter( 'post_link', 'my_awesome_permalink', 10, 3 );

Now, our custom permalink structure is ready. It will become www.example.com/post/{%post_id%}/{%post_title%} e.g.: www.example.com/post/25/my-awesome-post-title . We will need to add proper rewrite rule to make WP understand and return the right post.

add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
    $new_rules['^post/([0-9]+)/([^/]+)/?'] = 'index.php?p=$matches[1]';
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite;
}

With above code, you will be able to make your post permalink structure to www.example.com/post/25/my-awesome-post-title and it will show correct post.

One problem with above code is, you won’t be able to edit post slug from post editor. But your post url now comes from post title, which is editable!

Leave a Comment