🔗 Beautiful URLs for Everything
Want /events/2024/summer-festival instead of /?post_type=event&event_id=123? Rewrite rules create clean, SEO-friendly URLs.
📝 Basic Rewrite Rule
function add_custom_rewrite_rules() {
add_rewrite_rule(
'^events/([0-9]{4})/([^/]+)/?$',
'index.php?post_type=event&year=$matches[1]&event_slug=$matches[2]',
'top'
);
}
add_action('init', 'add_custom_rewrite_rules');
// Add query vars
function add_query_vars($vars) {
$vars[] = 'year';
$vars[] = 'event_slug';
return $vars;
}
add_filter('query_vars', 'add_query_vars');
// Flush rules after adding (visit Settings → Permalinks once)
🎯 Example: Location-based URLs
// URL: /stores/new-york/electronics
add_rewrite_rule(
'^stores/([^/]+)/([^/]+)/?$',
'index.php?post_type=store&city=$matches[1]&category=$matches[2]',
'top'
);
// URL: /product/category/laptops/gaming
add_rewrite_rule(
'^product/category/([^/]+)/([^/]+)/?$',
'index.php?product_category=$matches[1]&subcategory=$matches[2]',
'top'
);
✅ Debugging Rewrite Rules
// View all rewrite rules
$rules = get_option('rewrite_rules');
echo '' . print_r($rules, true) . '
';
// WP-CLI commands
wp rewrite list
wp rewrite flush
// Test URL matching
$match = preg_match('/^events\/([0-9]{4})\/([^\/]+)/', '/events/2024/summer', $matches);
var_dump($matches);
💡 Important: Flush Rules Only Once
- Never put
flush_rewrite_rules()on every init (performance killer) - Use
register_activation_hook()to flush on plugin activation - Or simply visit Settings → Permalinks and click Save
- Use
add_rewrite_rule()insideinithook
“URLs were /?location_id=123&type=event. Rewrote to /events/new-york/summer. SEO improved, users remembered URLs, shareable links made sense.”
