404 error - How do I redirect the browser to 404 page, if no posts are found in home page

admin2025-01-08  4

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/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

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

Share Improve this question edited Jul 26, 2021 at 19:31 MT09 asked Jul 26, 2021 at 19:26 MT09MT09 134 bronze badges 1
  • Any ideas? Thanks – MT09 Commented Jul 28, 2021 at 12:01
Add a comment  | 

1 Answer 1

Reset to default 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

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736269771a1377.html

最新回复(0)