The Rewrite API is a method to help developer manipulate URL structures also known as permalinks for custom post types, taxonomies. It is a critical component of WordPress and used extensively to create user-friendly and SEO-Optimized permalinks.
How Rewrite API works?
The Rewrite API allows developers to add their own rewrite rules and tie them to a specific query variables. When a user visits a URL, WordPress looks through these rewrite rules to determine which content to display, based on the matched pattern.
Rewrite Rules: These are patterns that define the URL structure for our content. They are added through the add_rewrite_rule()
function.
Query Vars: Query variables are part of the URL, typically in the form of key-value pairs, used to retrieve specific content. Developers can define custom query variables using add_rewrite_tag()
.
Flush Rewrite Rules: After making changes to rewrite rules, we need to flush them to apply the new settings. This is done through the flush_rewrite_rules()
function.
Using Rewrite API
Creating Custom Permalinks for CPT
It is one of the most common use case of Rewrite API. When registering a CPT we can use the rewrite
parameter to add rewrite rules.
function my_custom_post_type() { $args = array( 'public' => true, 'rewrite' => array('slug' => 'my-custom-posts'), 'label' => 'Custom Posts' ); register_post_type('custom_post', $args); } add_action('init', 'my_custom_post_type');
Similarly for Custom Taxonomies we can use:
function my_custom_post_type() { $args = array( 'public' => true, 'rewrite' => array('slug' => 'my-custom-posts'), 'label' => 'Custom Posts' ); register_post_type('custom_post', $args); } add_action('init', 'my_custom_post_type');
Redirecting URLs
Another practical application of the Rewrite API is for handling redirects. For example, if we need to redirect URLs we can use the add_rewrite_rule()
function to create redirects.
function custom_redirect() { add_rewrite_rule('^old-page/?$', 'index.php?pagename=new-page', 'top'); } add_action('init', 'custom_redirect');
Adding Custom Query Variables
We might need custom query variables to handle specific requests from our URL. With the Rewrite API, we can define these variables using add_rewrite_tag()
.
function add_custom_query_var($vars) { $vars[] = 'my_custom_var'; return $vars; } add_filter('query_vars', 'add_custom_query_var');
Conclusion
The Rewrite API in WordPress is an essential tool for developers looking to create custom URL structures, improve SEO, and redirect users from outdated content. By understanding how to utilize the Rewrite API, we gain full control over how WordPress handles permalinks, allowing us to customize our website.
Leave a Reply