If you’ve updated your WordPress permalinks from
/postname/ → /category/postname/,
you may notice old links returning 404 errors. That’s because WordPress can’t automatically redirect visitors to the new category-based URLs.
Here’s a quick fix that keeps your SEO intact and sends users to the right place.
⚙️ Step-by-Step
Log in to your WordPress admin.
Go to Appearance → Theme File Editor (or access your site files via FTP).
Open your theme’s functions.php file.
Paste the code below at the bottom:
add_action('template_redirect', function() {
if (is_404()) {
global $wpdb;
$request_uri = trim($_SERVER['REQUEST_URI'], '/');
$slug = basename($request_uri);
$post_id = $wpdb->get_var($wpdb->prepare(
"SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_status = 'publish' LIMIT 1",
$slug
));
if ($post_id) {
wp_redirect(get_permalink($post_id), 301);
exit;
}
}
});
Now, any visitor who lands on an old /postname/ URL will be automatically redirected to the correct /category/postname/ version — no broken links, no SEO loss.
Simple, quick, and future-proof.