How to Use the add_rewrite_rule() Function in WordPress
The add_rewrite_rule()
function in WordPress is used to create new rewrite rules in the WordPress URL system. This function allows us to construct custom URLs and attach them to specific content. For instance, if we want to create a specific URL for displaying a specific category or a specific post, we can take advantage of this function.
In fact, this function allows us to create URLs with a specific structure, and as a result, it enables better management of the URLs. For example, suppose you want to create a custom URL for displaying your site's news articles. By using add_rewrite_rule()
, you can easily accomplish this task and have that URL display the desired content.
Furthermore, after adding new rules, we also need to use the flush_rewrite_rules()
function so that WordPress recognizes the new rules. Therefore, it is very important that after every addition or modification of URL rules, we do not forget to call this function.
Now, let’s see how we can utilize this function. For example, we would like to add a resource for displaying specific posts with a custom URL. This can be done by using the following code:
function custom_rewrite_rule() {
add_rewrite_rule('^news/([^/]*)/?', 'index.php?pagename=news&slug=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_rule');
function custom_flush_rewrite_rules() {
flush_rewrite_rules();
}
add_action('init', 'custom_flush_rewrite_rules');
In this code, we have defined the function custom_rewrite_rule()
, which adds a new rule for news URLs. Then, using add_action()
, we can link this function to init
. Additionally, we define another function for flush_rewrite_rules()
that ensures the new rules are correctly recognized.
By executing this code, now you can have new URLs like yourdomain.com/news/some-slug that directly access the specific content you want. This feature allows you to create user-friendly URLs for your site and enhance the user experience.