Please create a redirect rule for functions.php in WordPress so the /locations page go…
- User
Please create a redirect rule for functions.php in WordPress so the /locations page go to home
- Assistant
Certainly! To redirect the
/locationspage to the homepage in WordPress via thefunctions.phpfile, you can add the following code snippet:function redirect_locations_to_home() { if (is_page('locations')) { wp_redirect(home_url()); exit; } } add_action('template_redirect', 'redirect_locations_to_home');Explanation:
is_page('locations')checks if the current page slug islocations.wp_redirect(home_url())sends a redirect to the homepage URL.exit;ensures no further code is processed after the redirect.- The hook
template_redirectis used because it runs before the template is loaded, ideal for redirects.
Add this code to your active theme’s
functions.phpfile, ideally in a child theme to avoid losing changes on theme updates. - User
It's not working, I'm still able to visit /locations
- Assistant
If the redirect is not working as expected, here are a few possible reasons and solutions:
- Confirm the page slug: Make sure the page slug is exactly
locations. If it differs (e.g., capital letters, trailing slash), the conditionis_page('locations')might fail. - Caching: Sometimes browser or server caching prevents immediate updates.
- Conflict with other plugins or theme code.
Let's try a more robust version:
function redirect_locations_to_home() { if (is_page() && (get_query_var('pagename') === 'locations' || $_SERVER['REQUEST_URI'] === '/locations' || $_SERVER['REQUEST_URI'] === '/locations/')) { wp_redirect(home_url(), 301); exit; } } add_action('template_redirect', 'redirect_locations_to_home'); - Confirm the page slug: Make sure the page slug is exactly