Adding category to customized permalink for specific category

I’m trying to make my news section include the post ID in the permalink. I found this great bit of code: Change permalinks structure for specific category.

However, it removed the /news/ from the permalink while adding the post ID. How do I add /news/ to the permalink?

I’ve tried adding:

. $category->name . ‘/’

between

‘/’ . $post->post_name

but that didn’t do it.

Also, the previous author stated the second part would rewrite the post ID to be in the format of /index.php?p=1234 but it doesn’t either.

#if news category, add post ID to permalink

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(‘/’ . $post->post_name .’-‘. $post->ID .’/’ ) );
}
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;
}

Thank you!

Read more here:: Adding category to customized permalink for specific category

Leave a Reply

Your email address will not be published. Required fields are marked *