I need to change my permalink structure just for one category. Now I have: /%postname%/
, but for News category I need this structure: /%postname%-%post_id%/
.
Question: how to add %post_id% in specific category?
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityThis 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('/'. $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;
}
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.
/postname-149/
but gives a 404 when the link is clicked. Is something not being translated to /index.php?p=1234
still?
If you want it only for one category I think the easiest way is to use wp_insert_post_data or save_post to hook to the slug-generation of the post and simply add the $post->ID
if the post has the category you look for.
This is the only solution I'm currently aware of, because AFAIK all the other core functions to manipulate the permalink structs can't be easily used only for one category.
Here is another question which has some more details on changing the slug on post update.
Why not just add the post id then? If that's all you need? You could just do this with query_vars
.
add_filter('query_vars', 'my_query_vars' );
You only need to check if you are in the 'special' category and if yes, add the var. Then utilizing the pre_get_posts
hook, check if your post contains an ID and if yes change your query to get desired post.