0

I have a normal page with content that can be maintained by editors via the backend. Now I want to display this content on the 404 page.

So i tried to use the pre_get_posts hook to alter the main query, but Conditional Tags like is_404() seem not to work there. Here is my action:

function load_error_page_content($query) {

    if ( !is_admin() && $query->is_404() && $query->is_main_query() ) {
        $query->set( 'page_id', 150 );
    } 

} add_action( 'pre_get_posts', 'load_error_page_content' );

If I remove && $query->is_404() I can see that the query altering works. But the header 404 is lost.

Does someone tried this before? Maybe I should use another hook to achieve this. The wp action, for instance. But then the main query is already done. What would be the best way to achieve this?

  • is_404 can be set by WordPress only after running the main query as that is the only way to find out if a post or page exists. Because pre_get_posts is called before the query is_404 is always false within that hook. – freejack Sep 19 '19 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.