Change permalinks structure for specific category

This can be accomplished with some custom filters & actions.

Try placing this code in your theme’s functions.php file:

add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
    // Get the categories for the post
    $category = get_the_category($post->ID); 
    if (  !empty($category) && $category[0]->cat_name == "News" ) {
        $permalink = trailingslashit( home_url("https://wordpress.stackexchange.com/". $post->post_name .'-'. $post->ID ."https://wordpress.stackexchange.com/" ) );
    }
    return $permalink;
}
add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
    // This rule will will match the post id in %postname%-%post_id% struture
    $new_rules['^([^/]*)-([0-9]+)/?'] = 'index.php?p=$matches[2]';
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite;
}

This will set up the permalink structure that you want for posts in the News category, and will also translate a request URI that looks like this:

/news-headline-text-01234

into this:

/index.php?p=1234

Source: This question was already asked on wordpress.org and my answer is based on the solution provided there.

Edit: Updated rewrite regex and rule to match the post id in a %postname%-%post_id% link structure.2 The current code is tested and confirmed.

Leave a Comment