简体   繁体   中英

How to redirect 404 not found page to the home page in Wordpress

I have a 404 error page which I don't want to use. Instead, I want to have the 404 page reload to my home page. I inserted the lines below in the beginning of the 404 php file:

<?php
/* Redirect browser */

echo '<script type="text/javascript">
           window.location = "http://www.google.com/"
      </script>';

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

This works (it will load to my homepage. However, the new page will reload and a new tab page will open.

I want to have the page reload and NOT to open a new tab.

How can I do this?

Thank in advance

You could use is_404 Docs function and hook it in the template_redirect Docs hook. If it returns true you could use wp_safe_redirect Docs function to redirect to the home/front page.

add_action('template_redirect', 'redirecting_404_to_home');

function redirecting_404_to_home()
{
    if (is_404()) 
    {
        wp_safe_redirect(site_url());
        exit();
    }
};

Code goes onto the functions.php file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM