Custom rewrite rules in WordPress allow you to define custom URLs for specific pages or posts on your site. This can be useful for creating more user-friendly URLs or for creating vanity URLs. Here’s an example code snippet to add custom rewrite rules in WordPress:
function wpsnippets_custom_rewrite_rules() {
add_rewrite_rule( '^my-page$', 'index.php?page_id=123', 'top' );
add_rewrite_rule( '^my-post/([^/]*)/?', 'index.php?p=456&my_var=$matches[1]', 'top' );
}
add_action( 'init', 'wpsnippets_custom_rewrite_rules' );
In this code snippet, we define a function wpsnippets_custom_rewrite_rules
that sets two custom rewrite rules using the add_rewrite_rule
function.
The first rewrite rule matches a URL of my-page
and redirects it to the page with ID 123 using the page_id
query variable. The second rewrite rule matches a URL of my-post/{post-slug}
and redirects it to post ID 456 using the p
query variable. We also capture any text after the /
as the my_var
query variable using the $matches
array.
Note that the third parameter of add_rewrite_rule
sets the position of the rewrite rule. In this example, we set it to top
to make sure that the custom rules take priority over other rewrite rules.
Finally, we add the wpsnippets_custom_rewrite_rules
function to the init
action using the add_action
function to ensure that the rewrite rules are added at the appropriate time during WordPress initialization.
With this code in place, visiting the URLs my-page
and my-post/{post-slug}
will redirect to the specified pages or posts on your site. You can modify the add_rewrite_rule
function to match the URLs you want to redirect and the query variables you want to use.