
Function.php WordPress used to work - REDIRECT 404 to Parent CAT
- or -
Post a project like this1685
£20(approx. $26)
- Posted:
- Proposals: 4
- Remote
- #3189721
- PRE-FUNDED
- Awarded
Description
Experience Level: Entry
Hi.
I have this code in FUNCTIONS.php that detects a 404 error and REDIRECTS (with a 301) to the parent CATEGORY
It still works - BUT - if the parent is ROOT (home) it redirects it there too ... I want 404 error to show if it's a genuine 404 like this https://chronodivers.com/thisisrubbish
For anything else I want it to redirect to the PARENT CATEGORY - as this does https://chronodivers.com/omega/omega-seamaster-planet-ocean-watch-sales/thisisRUBBISH
The code used is as follows
/**
* Add REDIRECT to PARENT
*/
function __404_template_redirect()
{
if( is_404() )
{
$req = $_SERVER['REQUEST_URI'];
if ( is_file( $req )) {
return; // don't reduce perf by redirecting files to home url
}
// pull the parent directory and convert to site url
$base_dir = dirname( $req );
$parent_url = site_url( $base_dir );
// redirect to parent directory
wp_redirect( $parent_url, 301 );
exit();
}
}
add_action( 'template_redirect', '__404_template_redirect' );
I am happy to edit the functions.php file with the correct code
Cheers
Tristan
I have this code in FUNCTIONS.php that detects a 404 error and REDIRECTS (with a 301) to the parent CATEGORY
It still works - BUT - if the parent is ROOT (home) it redirects it there too ... I want 404 error to show if it's a genuine 404 like this https://chronodivers.com/thisisrubbish
For anything else I want it to redirect to the PARENT CATEGORY - as this does https://chronodivers.com/omega/omega-seamaster-planet-ocean-watch-sales/thisisRUBBISH
The code used is as follows
/**
* Add REDIRECT to PARENT
*/
function __404_template_redirect()
{
if( is_404() )
{
$req = $_SERVER['REQUEST_URI'];
if ( is_file( $req )) {
return; // don't reduce perf by redirecting files to home url
}
// pull the parent directory and convert to site url
$base_dir = dirname( $req );
$parent_url = site_url( $base_dir );
// redirect to parent directory
wp_redirect( $parent_url, 301 );
exit();
}
}
add_action( 'template_redirect', '__404_template_redirect' );
I am happy to edit the functions.php file with the correct code
Cheers
Tristan
Tristan H.
100% (36)Projects Completed
36
Freelancers worked with
22
Projects awarded
56%
Last project
23 Oct 2025
United Kingdom
New Proposal
Login to your account and send a proposal now to get this project.
Log inClarification Board Ask a Question
-
There are no clarification messages.
We collect cookies to enable the proper functioning and security of our website, and to enhance your experience. By clicking on 'Accept All Cookies', you consent to the use of these cookies. You can change your 'Cookies Settings' at any time. For more information, please read ourCookie Policy
Cookie Settings
Accept All Cookies