Render 404 template on author pages - functions.php

Hello

I have a Sage 10 site I’m working on where there is the requirement of disabling WordPress author pages (/author/username/). Currently, I am using a function to prevent the page from loading and setting 404 headers, title, etc.


function my_404()
{
  header("Status: 404 Not Found");
  $GLOBALS['wp_query']->set_404();
  status_header(404);
  nocache_headers();

}


function no_author_page() {
  global $wp_query;

  if (is_author()) {
    my_404();
  }
}

However, the custom 404 template does not load as it does when any other really non-existant URL. Instead, the layout loads without content (header, footer with no content).

How can I get the 404 template rendered? I tried including get_404_template() but it didn’t render just loaded the template. Any suggestions? Thank you for your time reading this

I suggest doing some research and seeing how it’s being approached in other plugins.

Disable Author Archives – WordPress plugin | WordPress.org looks like it does exactly what you want and the source is 36 lines and easy to implement yourself if you don’t want to use the plugin.

Hi, @Log1x: Thanks for your response. I have replaced my code for the plugin code on the functions.php file and the result is the same: I only get a blank layout template, 404 title, but no 404 page error content.

Is there any way to properly load Sage/Laravel templates (404) into the content from functions.php?

Are you putting it at the bottom of functions.php so Sage/Acorn can be loaded first?

I’d suggest putting something like this in an mu-plugin or just using the plugin I linked above. It has no admin menu or any other bloat – it simply just does it’s job.

I just removed the function and tried the plugin instead, but I get the same result: an empty layout with header, footer, etc. but no content. I also tried re-placing the code in the end of the functions.php file. I tried including the 404 template file at the end of the function but it was not rendered properly either.

Updated. This is the final code that worked out for me:

/* Return 404 status code and template for existing author pages */

add_action(
  'template_include',
  function () {
    if (!empty($_GET['author']) || is_author()) {
      global $wp_query;

      $wp_query->set_404();
      $wp_query->post_count = 0;

      status_header(404);

      $template = get_404_template();
    } elseif(is_404()) {
      $template = get_404_template();
    } else {
      $template = get_page_template();
    }
    return $template;
  },
  1
);