1

I am listing posts on the homepage with pagination and if no posts are found on the home page. I want to redirect the page to 404 page and get 404 response code.

For example, example.com/page/200 Page number is 200 but there is no have 200 pages in the posts. I using two WP queries on the home page, I want to do that for the main query.

I want to redirect 404 page and get 404 response instead of "show no result text".

It's working on category page but I couldn't do it for homepage. Thank you

1
  • Any ideas? Thanks
    – MT09
    Jul 28, 2021 at 12:01

1 Answer 1

0

Well, detecting a 404 from .htaccess isn’t possible. This is because the .htaccess file is going to route any requests for non-existing pages to the index.php file. From there, WordPress will do a lookup in the database to see if the current request matches any content in the database.

If not, then WordPress returns a 404. Handling requests for non-existing pages in .htaccess would mean that WordPress would never load. As such, you’d have to handle the redirection login within WordPress itself.

I’d recommend the following plugin: https://wordpress.org/plugins/all-404-redirect-to-homepage/ (you can redirect to a specific page, not just the homepage).

or you can add this code but is not really going to work:

ErrorDocument 404 http://www.example.com/error.html

Instead, try this php code in functions.php

add_action( 'wp', 'se344018_redirect_404' );
function se344018_redirect_404()
{
    if ( is_404() ) {
        wp_redirect( home_url() );
        //
        // wp_redirect( home_url('some/page-slug') );
        exit;
    }
}

I found the code in https://ananchor.com 👍

1
  • I think this is the opposite of the question, isn't it? (which doesn't mention htaccess?) OP wants to return the home page as 404 if there are no posts, not redirect 404s to the home page.
    – Rup
    Nov 1, 2021 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.