0

First, I'm not trying to redirect the user as I don't want the URL to change - think of it as an include rather than a redirect. Second, I would want to have control over the content, title, etc. So the use case is this:

  1. If a user tries to access a page not found, it instead loads a specific page e.g I go to siteurl/hello-earth it loads the hello-world page but the URL does not change.
  2. If a user tries to access a page that exists, everything goes normally

This is what I'm using right now and everything works properly except the fact that the post meta where the category and date of publishing is displayed is not shown. The title, the content, the page title, the comments section everything is shown but the post meta. Any idea how to fix this?

add_action( 'template_redirect', function(){
    global $wp_query;
    if ( is_404() ){
        $id = 1; // the post corresponding to hello-world

        if ( $id ) {
            $wp_query->is_404 = false;
            status_header(200);
            header("HTTP/1.1 200 OK");

            $wp_query = new \WP_Query();
            $wp_query->query("page_id=$id&post_type=post");
            $wp_query->the_post();
            rewind_posts();
        }
    }
}, 999);

EDIT: This is a common problem no matter what theme I use. I have tested on twentytwentythree and twentytwentytwo. There are no other plugins active.

UPDATE: It looks like the problem is wp_query->is_single is being set to false (but wp_query->is_singular is true, just like for a valid page) so WP decides not to display the post meta data.

1 Answer 1

1

This is the final code that works. I had to set $wp_query->is_single = true; manually:

add_action( 'template_redirect', function(){
    global $wp_query;
    if ( is_404() ){
        $id = 1; // the post corresponding to hello-world

        if ( $id ) {
            $wp_query->is_404 = false;
            status_header(200);
            header("HTTP/1.1 200 OK");

            $wp_query->query("page_id=$id&post_type=post");
            $wp_query->the_post();
            $wp_query->is_single = true;
        }
    }
}, 999);

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.