I need a function to paste in my theme that automatically rename the base category permalink from category to genre after activating the theme, example:
http://localhost/category/drama/
to
http://localhost/genre/drama/
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 communityI need a function to paste in my theme that automatically rename the base category permalink from category to genre after activating the theme, example:
http://localhost/category/drama/
to
http://localhost/genre/drama/
So you can quickly achieve this by changing 'category' to 'genre' you can do this in Settings > Permalinks and change 'Category Base' to 'genre'.
To do it with code and keep both 'category' and 'genre' as prefixes is possible with a rewrite rule, however someone else may know a better way. You also need to only run flush_rewrite_rules() once so you need to take care of only calling this code when you change the rewrite rule!
This works for me in functions.php:
function add_category_base() {
add_rewrite_rule('^genre/([^/]+)/?', 'index.php?taxonomy=category&term=$matches[1]', 'top');
flush_rewrite_rules();
}
add_action('init', 'add_category_base', 10, 0);
As I said, you should not run flush_rewrite_rules all the time as it does a lot of stuff and only needs to be run when you change the rule.