2

I have a custom 404 error page, and I just want a quick module that hides the 404 page title, if the user arrives at a 404 error.

I've found a D7 function that looks like it would work, checking for '404 Not Found' in the http header, and adding a class that I can target with CSS. But I'm not sure how I'd do something like this for D8.

Here's what I've got:

function MYMODULE_preprocess_html(&$variables) {
  $headers = drupal_get_http_header();

  if (isset($headers['status']) && $headers['status'] == '404 Not Found') {
    $variables['classes_array'][] = 'page-404';
  }
}
2
  • One way to do this is add twig template suggestions for a 404 response, create that twig file and not print the region that normally has the title block. I’m on mobile so o have no code in front of me.
    – Kevin
    Commented Sep 4, 2019 at 5:00
  • Hiding the title with CSS isn't hiding it from search engines or screen readers.
    – leymannx
    Commented Sep 4, 2019 at 9:16

2 Answers 2

4

I don't think you need a custom module for something like this... This should be as easy as:

  1. Go to Configuration -> System -> Basic Site Settings, get the page URL you have for the 404 page.

  2. Go to Structure -> Block Layout, edit the 'Page Title' block, and exclude it under the Visibility section, by page URL from step1.

3
  • already tried. it doesn't work. because the page doesn't load the 404 page URL. It simply replaces expected content with the 404 content. If I go to website.com/randompagename , it drops in the 404 error, but still has the same url.
    – turpentyne
    Commented Sep 4, 2019 at 3:43
  • 2
    You can do it this way in UI, but you need a contrib module for the visibility condition: drupal.org/project/block_in_page_not_found
    – 4uk4
    Commented Sep 4, 2019 at 6:21
  • @4k4 ..ah! dang it! I know the module, but forgot that it has a 'negate' option! That did the trick.
    – turpentyne
    Commented Sep 4, 2019 at 17:07
2

This should work:

/**
 * Implements hook_preprocess_HOOK().
 */
function modulename_preprocess_html(&$variables) {
  $status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
  if($status && $status->getStatusCode() == '404') {
    if(!$variables['attributes']) {
      $variables['attributes'] = new Attribute();
    }
    $variables['attributes']->addClass('page-404');
  }
}

credits go to: How to check if the current page is a 404 error from a module/template?

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.