Using WP_Rewrite::set_category_base() in WordPress

wordpress wp rewrite set category base
21 January 2025

Introduction to WP_Rewrite::set_category_base()


In the world of WordPress, URL settings are of great importance. One of the key classes in this area is the WP_Rewrite class. This class is responsible for managing and customizing the permalink structure in WordPress. One of the important methods of this class is the set_category_base() method, which allows us to set a base for our category slugs.


Simply put, each category in WordPress can have a specific URL, and this URL can include a base section. By using the set_category_base() method, you can customize this base and set your category URLs to a more appealing format. This not only helps with SEO for your website but also provides users with a better experience.


For example, suppose you want to change the default 'category' base to 'topics'. This can be achieved with the set_category_base() method. Consequently, your category URLs would take the form of example.com/topics/category-name.


To utilize this method, you can initially add an action to init and then apply your custom settings. Therefore, to ensure that these changes are in effect, after making the modifications, you must flush the rewrite_rules.


Code Example


function custom_category_base() {
global $wp_rewrite;
$wp_rewrite->set_category_base( 'topics' );
}
add_action( 'init', 'custom_category_base' );

Code Explanation



Function custom_category_base: function custom_category_base() { creates a new function named custom_category_base. This function allows us to change the default category base settings.


Accessing $wp_rewrite: global $wp_rewrite; allows us to access the $wp_rewrite variable that references the WP_Rewrite class, enabling access.


Setting Category Base: $wp_rewrite->set_category_base( 'topics' ); by using this line, we change the default category base to 'topics'.


Adding Action: add_action( 'init', 'custom_category_base' ); this line adds the custom_category_base function to the 'init' action so that it executes during the WordPress initialization process.

FAQ

?

Why should I use WP_Rewrite?

?

Does changing the category base affect SEO?

?

Is it easy to change the category base?