Как настроить ошибку 404 на вордпресс

WordPress 404 страница - как настроить

Рассмотрим, как настроить шаблон ошибки 404 в WordPress, чтобы создать полезную страницу, которая поможет пользователям сориентироваться на вашем сайте и улучшить поведенческие факторы.

Что такое ошибка 404 и почему важно правильно настроить страницу?

Ошибка 404 возникает, когда посетитель пытается получить доступ к странице, которая не существует. Многие склонны игнорировать эту страницу при использовании шаблонов WordPress и не задумываются о ее существовании. Тем не менее, если вы потратите время на создание удобной страницы 404, это поможет задержать пользователя на вашем сайте.

Интернет-адрес, ведущий на страницу с ошибкой 404, может оказаться просто неправильно набранным URL либо возникнуть со временем, если вы удалили проиндексированную страницу и забыли об этом. При выдаче кода 404 WordPress настроен на автоматический поиск файла 404.php. Базовый шаблон с этой ошибкой включен в некоторые темы WordPress. Если же этого файла нет, то будет показано системное сообщение, которое не несет полезной для пользователя информации.

Как создать страницу 404 ошибки, если ее нет в шаблоне — настройка

Не все темы WordPress имеют собственный файл шаблона ошибки 404. Если разработчик темы предусмотрел это, такой файл будет называться 404.php. WordPress автоматически использует эту страницу, когда возникает ошибка 404. Если в вашей теме нет этого файла, его можно создать самостоятельно.

шаблон 404 вордпресс

  1. Первое, что нужно сделать, это сформировать настраиваемый шаблон, например, редактируя файл 404.php, скопированный из другой темы. Если вы редактируете свою тему напрямую, настоятельно рекомендуется сделать резервную копию темы WordPress.
  2. Файл ошибки 404 расположен по адресу: /wp-content/themes/имя-темы/404.php
  3. Страница ошибки примет стиль активной темы, поскольку она вызывает шапку
  4. И подвал текущей темы.
  5. Понадобится только отредактировать заголовок и сообщение на странице в соответствии с вашими конкретными потребностями.
  6. Для этого откройте файл шаблона ошибки 404 в редакторе кода и измените текст сообщения на свое усмотрение.
  7. Добавьте в шаблон строку поиска, если ее там нет. Затем сохраните файл и загрузите его в каталог темы установки WordPress.

Поскольку все темы различаются, нет никакой гарантии, что простое копирование файла шаблона 404.php будет работать. Чтобы сервер нашел страницу 404, добавьте следующую строку в файл .htaccess:

ErrorDocument 404/index.php?error=404

Файл index.php расположен в корневой папке вашего сайта. Если WordPress находится в подкаталоге с именем «wordpress», код, добавляемый в файл .htaccess, должен быть:

ErrorDocument 404/wordpress/index.php?error=404

Что разместить на wordpress странице 404

Когда пользователь обнаруживает вместо искомой страницы сообщение об ошибке 404, разочарование может заставить его покинуть ваш сайт преждевременно. Задача веб-мастера помочь найти посетителю информацию, которую он искал, и тем самым снизить процент отказа и улучшить поведенческие факторы на сайте.

Рекомендуется указать пользователю правильное направление действий, которое заставит его задержаться на сайте. Это можно сделать несколькими способами:

  • предоставить информацию о других разделах вашего интернет-ресурса, которые можно посмотреть;
  • дать посетителю возможность связаться с вами по указанным контактным данным;
  • добавить ссылки на популярные сообщения, последние комментарии, архивы;
  • разместить строку поиска, чтобы посетитель сам нашел нужную информацию на сайте.

Чтобы сделать страницу уникальной, вы можете снабдить ее фоновым изображением в стиле оформления сайта. Допустимо также использовать html-теги и css-стили, чтобы придать шаблону индивидуальность.

Как создать в вордпресс 404 страницу при помощи плагина

Создать собственную страницу 404, как и любую другую страницу в WordPress можно при помощи плагина 404page (https://wordpress.org/plugins/404page/). Важной особенностью этого плагина является то, что он не создает перенаправление, а формирует правильный ответ сервера с кодом 404. Он сообщает поисковым системам, что страница не существует и должна быть удалена из индексирования, тогда как перенаправление приведет к HTTP-коду 301 или 302 и URL-адрес останется в индексе поиска.

Установите плагин 404page из меню админки «Плагин -> Добавить новый» и активируйте его.

плагин 404 вордпресс

Создайте страницу 404 как обычную страницу WordPress из меню «Страницы -> Добавить новую». Внесите в нее всю необходимую информацию, которую вы хотите показать посетителю, и нажмите кнопку «Опубликовать». Плагин 404page также добавляет CSS-класс error404 в тег <body>, который можно использовать для задания дополнительных стилей на странице.

страница 404 вордпресс

После активирования плагина в меню «Внешний вид» (1) появился раздел «404 Error Page» (2), в котором можно настроить отображение страницы ошибки.

Выберите созданную страницу 404 из списка страниц сайта (3). Убедитесь, что отмечен флажок (4), чтобы сервер отдавал код 404 при доступе к этой странице. Если вы используете кэширование, плагин выдаст предупреждение – страница из кэша будет отдавать код 200, поэтому ее нужно исключить из кэширования.

При возникновении проблем или конфликта с другими плагинами 404page может быть запущен в режиме совместимости. Нажмите кнопку «Сохранить изменения» (5).

настройка 404 вордпресс

Чтобы включить обработку ошибок 404 в WordPress, нужно установить структуру ссылок в меню «Настройки -> Постоянные ссылки» на любой пункт, кроме «По умолчанию». В противном случае ошибка 404 обрабатывается сервером, а не движком WordPress.

iPipe – надёжный хостинг-провайдер с опытом работы более 15 лет.

Мы предлагаем:

  • Виртуальные серверы с NVMe SSD дисками от 299 руб/мес
  • Безлимитный хостинг на SSD дисках от 142 руб/мес
  • Выделенные серверы в наличии и под заказ
  • Регистрацию доменов в более 350 зонах

Languages:
English
Creating an Error 404 Page 日本語
(Add your language)

While you work hard to make sure that every link actually goes to a specific web page on your site, there is always a chance that a link clicked will slam dunk and become a famous 404 ERROR PAGE NOT FOUND.

All is not lost. If your visitors encounter an error, why not be a helpful WordPress site administrator and present them with a message more useful than «NOT FOUND».

This lesson will teach you how to edit your «error» and «page not found» messages so they are more helpful to your visitors. We’ll also show how to ensure your web server displays your helpful custom messages. Finally, we’ll go over how to create a custom error page consistent with your Theme’s style.

Contents

  • 1 An Ounce of Prevention
  • 2 Understanding Web Error Handling
  • 3 Editing an Error 404 Page
  • 4 Creating an Error 404 Page
  • 5 Tips for Error Pages
    • 5.1 Writing Friendly Messages
    • 5.2 Add Useful Links
  • 6 Testing 404 Error Messages
  • 7 Help Your Server Find the 404 Page
  • 8 Questions About Error Files

An Ounce of Prevention

Some errors are avoidable, you should regularly check and double check all your links. Also, if you are deleting a popular but out-of-date post, consider deleting the body of the post, and replacing it with a link referring visitors to the new page.

Understanding Web Error Handling

Visitors encounter errors at even the best websites. As site administrator, you may delete out-of-date posts, but another website may have a link to your inside page for that post.

When a user clicks on a link to a missing page, the web server will send the user an error message such as 404 Not Found. Unless your webmaster has already written custom error messages, the standard message will be in plain text and that leaves the users feeling a bit lost.

Most users are quite capable of hitting the back key, but then you’ve lost a visitor who may not care to waste their time hunting for the information. So as not to lose that visitor, at the very least, you’ll want your custom message to provide a link to your home page.

The friendly way to handle errors is to acknowledge the error and help them find their way. This involves creating a custom Error Page or editing the one that came with your WordPress Theme.

Editing an Error 404 Page

Every theme that is shipped with WordPress has a 404.php file, but not all Themes have their own custom 404 error template file. If they do, it will be named 404.php. WordPress will automatically use that page if a Page Not Found error occurs.

The normal 404.php page shipped with your Theme will work, but does it say what you want it to say, and does it offer the kind of help you want it to offer? If the answer is no, you will want to customize the message in the template file.

To edit your Theme’s 404 error template file, open it in your favorite text editor and edit the message text to say what you want it to say. Then save your changes and upload it to the theme directory of your WordPress install.

While you are examining and editing your 404 template file, take a look at the simple structure of the 404.php file that is shipped with Twenty Thirteen. It basically features tags that display the header, sidebar, and footer, and also an area for your message:

<?php
/**
 * The template for displaying 404 pages (Not Found)
 *
 * @package WordPress
 * @subpackage Twenty_Thirteen
 * @since Twenty Thirteen 1.0
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<div id="content" class="site-content" role="main">

			<header class="page-header">
				<h1 class="page-title"><?php _e( 'Not Found', 'twentythirteen' ); ?></h1>
			</header>

			<div class="page-wrapper">
				<div class="page-content">
					<h2><?php _e( 'This is somewhat embarrassing, isn’t it?', 'twentythirteen' ); ?></h2>
					<p><?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'twentythirteen' ); ?></p>

					<?php get_search_form(); ?>
				</div><!-- .page-content -->
			</div><!-- .page-wrapper -->

		</div><!-- #content -->
	</div><!-- #primary -->

<?php get_footer(); ?>

So, to change the error message your visitor sees, revise the text within the h1 heading and within the page-content class; if necessary, add more paragraphs below that.

Creating an Error 404 Page

If your WordPress Theme does not include a template file named 404.php, you can create your own.

Because every theme is different, there is no guarantee that copying over the 404.php template file found in the Twenty Thirteen Theme will work, but it’s a good place to start. The error page you copy from the Twenty Thirteen Theme will adopt the style of the current theme because it actually calls the header and footer of the current theme. That’s less work for you, and you may only have to edit the message to suit your particular needs.

To use the 404.php template file from the WordPress Twenty Thirteen Theme:

  1. Copy the file /wp-content/themes/twentythirteen/404.php into the directory of your current theme.
  2. Then, as described in the previous section, edit the error message to present your desired error message.

If copying the default 404.php into your theme directory does not work well with your theme, you can also:

  • Change the Default Theme’s 404.php template file’s header, sidebar, footer, and other codes to match the rest of the Theme’s layout.

Or

  • Copy the index.php file of your current theme to a file called 404.php.
  • Open that file and delete all sections dealing with posts or comments, see The Loop.
  • Then, edit your 404 error message.

Tips for Error Pages

There are various improvements you can make to your 404 Error web pages so let’s look at some of your options.

Writing Friendly Messages

When an error message is displayed, you can say many things to help a visitor feel reassured they’ve only encountered a minor glitch, and you’re doing the best you can to help them find the information they want. You can say something clever like:

"Oops, I screwed up and you discovered my fatal flaw. 
Well, we're not all perfect, but we try.  Can you try this
again or maybe visit our <a 
title="Our Site" href="http://example.com/index.php">Home 
Page</a> to start fresh.  We'll do better next time."

You should also attempt to show the user what they want. Check out the AskApache Google 404 Plugin to add google search results to your 404.php

Or, say something shorter and sweeter. Almost anything you say is better than 404 Error Page Not Found. You can find more information about writing 404 Error pages on the Internet, like List Apart’s Perfect 404.

As an implementation of the Perfect 404 page, this solution will tell the user it’s not their fault and email the site admin.
Helpful 404 page

When a visitor gets a 404 error page, it can be intimidating, and unhelpful. Using WordPress, you can take the edge off a 404 and make it helpful to users, and yourself, too, by emailing whenever the user clicks a link to a non-existent page.

<p>You 
<?php
#some variables for the script to use
#if you have some reason to change these, do.  but wordpress can handle it
$adminemail = get_option('admin_email'); #the administrator email address, according to wordpress
$website = get_bloginfo('url'); #gets your blog's url from wordpress
$websitename = get_bloginfo('name'); #sets the blog's name, according to wordpress

  if (!isset($_SERVER['HTTP_REFERER'])) {
    #politely blames the user for all the problems they caused
        echo "tried going to "; #starts assembling an output paragraph
	$casemessage = "All is not lost!";
  } elseif (isset($_SERVER['HTTP_REFERER'])) {
    #this will help the user find what they want, and email me of a bad link
	echo "clicked a link to"; #now the message says You clicked a link to...
        #setup a message to be sent to me
	$failuremess = "A user tried to go to $website"
        .$_SERVER['REQUEST_URI']." and received a 404 (page not found) error. ";
	$failuremess .= "It wasn't their fault, so try fixing it.  
        They came from ".$_SERVER['HTTP_REFERER'];
	mail($adminemail, "Bad Link To ".$_SERVER['REQUEST_URI'],
        $failuremess, "From: $websitename <noreply@$website>"); #email you about problem
	$casemessage = "An administrator has been emailed 
        about this problem, too.";#set a friendly message
  }
  echo " ".$website.$_SERVER['REQUEST_URI']; ?> 
and it doesn't exist. <?php echo $casemessage; ?>  You can click back 
and try again or search for what you're looking for:
  <?php include(TEMPLATEPATH . "/searchform.php"); ?>
</p>

Add Useful Links

If you encounter a «page not found» situation on the WordPress site, it is filled with helpful links to direct you to the various categories and areas of information within the WordPress site. Check it out at http://wordpress.org/brokenlink.php.

To add similar useful links to your 404 page, create a list, or a paragraph, so the visitor can easily determine which section might be useful to visit. Information of that nature is much better than having the user just reach a dead-end. To help you understand how to link to documents within your site, especially to Pages and Categories, see Linking_Posts_Pages_and_Categories.

Testing 404 Error Messages

To test your custom 404 page and message, just type a URL address into your browser for your website that doesn’t exist. Make one up or use something like:

http://example.com/fred.php

This is sure to result in an error unless you actually have a php file called fred. If your error page doesn’t look «right», you can go back and edit it so it works correctly and matches your Theme’s look and feel.

Help Your Server Find the 404 Page

By default, if WordPress cannot find a particular page it will look for the 404.php web page. However, there may be cases where the web server encounters a problem before WordPress is aware of it. In that case, you can still guarantee that your web server sends the visitor to your 404.php template file by configuring your web server for custom 404 error handling.

To tell your web server to use your custom error files, you’ll need to edit the .htaccess file in the main directory (where main index.php file resides) of your WordPress installation. If you don’t have an .htaccess file, see Editing Rewrite Rules (.htaccess) on how to create an .htaccess file.

To ensure the server finds your 404 page, add the following line to your .htaccess file:

ErrorDocument 404 /index.php?error=404

The url /index.php is root-relative, which means that the forward slash begins with the root folder of your site. If WordPress is in a subfolder or subdirectory of your site’s root folder named ‘wordpress’, the line you add to your .htaccess file might be:

ErrorDocument 404 /wordpress/index.php?error=404

Questions About Error Files

Why not just hard code the path all the way to the 404.php file?
By allowing index.php to call the error file, you ensure that the 404.php file used will change automatically as you change your theme.
What happens if I switch to a theme that does not have a 404.php file?
Visitors clicking on a broken link will just see a copy of the home page of your WordPress site (index.php), but the URL they see will be the URL of the broken link. That can confuse them, especially since there is no acknowledgement of the error. But this is still better than a getting a «NOT FOUND» message without any links or information that could help them find what they seek.

WordPress – Страница 404

Настало время настроить страницу ошибок 404 в WordPress. Сегодня поговорим о разных вариантах реализации данной страницы.

Вступление:

Независимо от того, насколько сильно вы пытаетесь создать идеальный сайт, вы, вероятно, уже поняли что это просто невозможно. Пока вы публикуете новый контент, новые страницы и меняете структуру своего сайта, возникают проблемы. Без исключений. Но не беспокойтесь! В конце концов, ваша задача сделать отличную работу, управляя всеми ее аспектами.

Сегодня давайте оставим другие ошибки и проблемы в стороне, и сосредоточимся на одной из наиболее распространенных проблем, с которой сталкиваются обычные пользователи Интернета во время просмотра. Даже те, у кого нет опыта работы в веб-технологиях, знают о 404 странице ошибок. Вы видели множество из них в своей онлайн-жизни, не так ли?

Задача сегодняшнего поста – настроить эту страницу ошибок и сделать ее более удобной для пользователя.

Что такое 404 страницы ошибок?

Когда конкретная страница не может быть найдена на вашем сайте, сервер будет отправлять сообщение об ошибке 404 браузеру. Это означает, что страница или сообщение не находятся на этом веб-сайте (больше вообще не находятся 🙂 ) . Обычно это происходит, когда пользователь вводит URL-адрес вашего сайта, но попадает на же удаленную страницу, которая ранее была проиндексирована поисковыми системами и связана с другими источниками.

WordPress – Страница 404

Например, если у вас есть контактная страница на сайте www.yoursite.com/contact, и кто-то пытается перейти на www.yoursite.com/contacts , WordPress сделает перенаправление на страницу 404.php.

Страница ошибки в WordPress по умолчанию

По умолчанию каждая тема WordPress поставляется с шаблоном 404.php, который отвечает за отображение сообщения об ошибке незадачливым читателям. К сожалению, эти страницы по умолчанию довольно скудны и содержат только основную информацию. Итак, если пользователь перешел на страницу 404.php, WordPress просто сообщит ему, что запрошенный ресурс не найден на сервере. Как вы можете видеть на скриншоте, страница 404 стоковой темы Twenty Seventeen не совсем приятна на вид. Вы просто должны изменить эту страницу, не так ли?

WordPress – Страница 404

Если вам повезет, тема, которую вы используете, уже содержит несколько 404 шаблонов страниц ошибок. Возможно, это даже позволит вам настроить страницу через удобный интерфейс. Но если это не так, не беспокойтесь. Сегодня я настроен показать Вам, как создать страницу самостоятельно и предоставить её в приятном для читателя виде.

Что делает хорошую страницу ошибок в WordPress?

Не все страницы ошибок одинаковы. Иногда обычного стиля будет достаточно, чтобы привлечь внимание ваших посетителей. Но более вероятно, что вам понадобится еще несколько элементов, чтобы все внешний вид страницы был приятен пользователям сайта. По моему опыту, хороший шаблон 404 должен иметь большинство следующих элементов:

  • Апология – пользовательское личное сообщение, хорошо видимое на странице

  • Изображение – (смешное) изображение, которое делает страницу с ошибкой менее страшной

  • Контакт – Показать контактную информацию или форму

  • Поле поиска – пусть люди ищут на Вашем сайте другой контент

  • Последние сообщения – позволяют посетителям открывать одну из последних статей

  • Популярные сообщения – позволяют посетителям увидеть ваши самые популярные записи

Очевидно, что элементы страницы будут зависеть от сайта. Иногда забавная картинка просто не может быть частью серьезных бизнес-сайтов, и иногда вы будете работать на сайтах, на которых вообще не будет сообщений в блоге. Но извлеките лучшее из списка и подумайте дважды, прежде чем добавлять элементы на странице 404.

Где черпать идеи для создания страницы 404?

Я столкнулся с некоторыми удивительными страницами ошибок, которые могут помочь вам получить идеи и глядя на них придумать свои решения. Как правило, это хорошая идея сделать вашу 404-страничную забавной. Поскольку вы должны признать ошибку, ваши посетители захотят увидеть что-то забавное на странице (это обычная психология)

WordPress – Страница 404

Если вы достигнете внимания посетителей, даже если они перешли на несуществующую страницу, вы можете быть уверены, что они останутся на более длительное время для просмотра сайта и вернутся снова. И, безусловно, вы можете сделать так, чтобы страница с ошибками была удобной, но об этом мы поговорим позже. На данный момент давайте посмотрим несколько примеров красиво разработанных 404 страниц ошибок:

Создайте собственной страницы ошибок 404

Во-первых, хотел бы напомнить, что изменение файлов вашей темы не является лучшей практикой. Прежде чем приступать к внесению изменений, хотел бы предложить использовать дочернюю тему. Когда вы создаете дочернюю тему для своего сайта, все изменения в ее файлах не будут затронуты обновлениями, которые вы будете устанавливать для вашей обычной темы. В этом случае создание файла 404.php в дочерней теме не повлияет на исходный, но файл все равно будет отображаться.

Не поймите неправильно, при изменении исходного файла изменений не будет. Но в этом случае обязательно создайте резервную копию, чтобы вы могли восстанавливать изменения после обновления.

Давайте сделаем вид, что вы не поленились и подготовили дочернюю тему. Итак, первый шаг – создать новый файл:

  1. Откройте папку, в которой вы создали дочернюю тему
  2. Создайте файл 404.php
  3. Откройте файл в удобном для Вас редакторе
  4. Скопируйте и вставьте следующий код:

    <?php get_header(); ?><div id="main-content"><div class="container"><div id="content-area" class="clearfix"><div id="left-area"><article id="post-0" <?php post_class( 'et_pb_post not_found' ); ?>><img  data-src="https://techblog.sdstudio.top/wp-content/uploads/2020/03/post-9340-5e76bb3f25a0a.png"><h1><?php esc_html_e('Page Not Found','WP Loop'); ?></h1><p><?php esc_html_e('Oh No! The page you opened does not exist. Please use the links below to navigate to a safer place.', 'WP Loop'); ?></p></article> </div> <?php get_sidebar(); ?></div> </div> </div> <?php get_footer(); ?>
  5. Измените путь к вашему изображению в строке # 7
  6. Изменить заголовок в строке $ 8
  7. Напишите пользовательское сообщение в строке # 9
  8. Сохраните изменения

Вы создали собственный шаблон. Если вы просматриваете страницу, все, что вы увидите, — это изображение, сообщение и стандартный заголовок, боковая панель и нижний колонтитул, которые у вас есть на всех других страницах. Тем не менее, это далеко не то, что я описал ранее, поскольку нет виджетов, поэтому придерживайтесь еще нескольких моментов, пока мы не создадим тот идеальный 404.php, который вы хотите. Кроме того, было бы неплохо добавить некоторые стили на страницу.

Добавление пользовательских виджетов

Хотя можно скопировать всю страницу с нуля, в этом нет необходимости. WordPress уже позволяет добавлять виджеты, которые помогут вам отображать самые последние и популярные статьи. Начиная с версии 4.8, вы даже можете добавлять мультимедиа в специализированные виджеты, так почему бы не воспользоваться этим?

Чтобы добавить новые виджеты специально на страницу 404.php , предлагаю создать новую виджетную область (пространство на вашей странице, которое позволяет добавлять виджеты). В некоторых случаях темы WordPress позволяют создавать новые виджетные области на панели управления. Итак, быстро взгляните в Appearance -> Widgets. Если вам повезет, у вас будет возможность создать эту область для вас. Если нет, давайте создадим её быстро, чтобы на вашей новой странице могли быть разные виджеты:

  1. Перейдите в папку вашей дочерней темы
  2. Откройте или создайте файл functions.php
  3. Скопируйте и вставьте код:

    function widget_area_404 () {register_sidebar (массивсив'name' => '404 Page','id' => '404','description' => __ ('Виджеты для страницы ошибки 404.'),'before_widget' => '<div class = "et_pb_post">','after_widget' => '</ div>','before_title' => '<h4 class = "widgettitle">','after_title' => '</ h4>',));}add_action ('widgets_init', 'widget_area_404');
  4. Сохранить изменения
  5. Откройте файл 404.php, который вы изменили ранее.
  6. Скопируйте и вставьте следующий код, где вы хотите показать новые виджеты (например, после названия и текста):

    <? php dynamic_sidebar ('404'); ?>
  7. Сохранить изменения

После того, как WordPress сообщит, где будет отображаться новая область виджета, настало время добавить виджеты. Итак, перейдите в Appearance -> Widgets , выберите «Недавние сообщения», «Популярные сообщения» или любой другой виджет, который вы хотели бы иметь на своей новой странице 404 (другой пример – бесплатный виджет Google Maps для показа вашего местоположения). Не забудьте настроить виджеты по своему вкусу и помните, что есть новые мультимедийные виджеты, если вы хотите добавить изображения, видео или аудиофайлы на страницу.

Используйте плагин для создания настраиваемой страницы 404

Если вы следовали всем шагам, поздравляю – у вас есть страница ошибки 404, которая будет загружена для любого из посетителей. Но даже если создание настраиваемого шаблона не так сложно, когда вам просто нужно скопировать и вставить код, который мы предоставили, многие из вас предпочтут работать в удобном для пользователя интерфейсе. В этом случае я хотели бы показать вам простой плагин, который будет создавать пользовательские 404 страницы для вас.

Плагин 404page — your smart custom 404 error page

WordPress – Страница 404

Этот плагин позволит вам легко создавать собственную страницу ошибок 404 без каких-либо усилий, которая будет адекватно работать практически с любой темой.

Затем перейдите на страницу «Внешний вид» -> «Страница ошибки 404» и выберите созданную страницу как свою страницу с ошибкой 404. Вот и все!

Загрузить плагин:

Smart Custom 404 error page [404page]

Создание страницы 404 при помощи виджетов и контента из KingComposer в теме Cactus

Зарегистрируйте новую область для применения виджета:

    register_sidebar( array('name' => '404 Page','id' => '404','description' => __( 'Widgets for 404 error page.' ),'before_widget' => '<div class="et_pb_post">','after_widget' => '</div>','before_title' => '<h4 class="widgettitle">','after_title' => '</h4>',    ) );

После регистрации данной области мы можем применить вывод виджетов при помощи:

  <?php dynamic_sidebar( '404' ); ?>

Далее откройте файл 404.php

И замените его содержание кодом ниже:

<?php    get_header();?><?php echo apply_filters('cactus_page_title_bar','','');?><div class="page-wrap"><?php do_action('cactus_before_page_wrap');?><div class="container"><div class="page-inner row no-aside"><div class="col-main"><section class="post-main" role="main" id="content"><article class="post-entry text-left"><?php dynamic_sidebar( '404' ); ?><a href="javascript:;" onClick="javascript :history.back(-1);"><span class="cactus-btn cactus-primary"><?php echo esc_attr('<< Назад', 'cactus');?></span></a><?php do_action('cactus_after_page_content');?></article></section></div></div></div></div><?php get_footer();

Далее создайте новую секцию в King Composer с любым содержанием, после чего добавьте в область виджета отображение секции. Для этого перейдите к виджетам и перетяните компонент “KC Content”:

WordPress – Страница 404

В область виджета для страницы 404:

WordPress – Страница 404

Когда компонент был перенесен введите в поле “Content Filters” название секции, у Вас под полем ввода должно появится выпадающее меню для выбора секции с похожим названием. Выберите секцию, для которой Вы подготовили контент.

Если по какой-то причине выпадающий список не отображается нажмите кнопку “Сохранить” и повторите попытку.

Источник записи:

Chances are high that you’ve landed on a 404 page and immediately left the website because it was less than helpful. A 404 page is what WordPress displays when someone enters or clicks on a URL that doesn’t exist on your website. This page is a generic error that just informs the visitor the page wasn’t found. In this article, we’ll explore how to create a custom 404 page for WordPress. Along the way, we’ll see both good and bad designs.

  • 1
    Why Create a Custom 404 Page for WordPress?

    • 1.1
      Generic 404 Page

  • 2
    Custom 404 Page Examples

    • 2.1
      1. Google

    • 2.2
      2. WordPress.org

    • 2.3
      3. WordPress.com

    • 2.4
      4. Elegant Themes

    • 2.5
      5. Twenty Twenty-One

    • 2.6
      6. Twenty Twenty

    • 2.7
      7. Slack

    • 2.8
      8. Amazon

  • 3
    404 Page Content

  • 4
    How to Create a Custom 404 Page in WordPress with the Divi Theme Builder

    • 4.1
      Importing a Custom 404 Page into the Divi Theme Builder

    • 4.2
      Creating a Custom 404 Page with the Divi Theme Builder

  • 5
    Ending Thoughts on Creating a Custom 404 Page for WordPress

Why Create a Custom 404 Page for WordPress?

It’s tempting to skip designing the 404 page because you hope no one will see it. However, it needs to be helpful to your visitors. It can be just as important as any other page. A general message is a bad user experience. It doesn’t look good and it gives them no reason to stay on your website.

First, let’s look at the generic page we’re trying to avoid.

Generic 404 Page

Generic 404 Page

The standard 404 page that WordPress displays is just an error message. It’s placed within the body content area and shows your header, footer, and sidebars if you have them.

Unfortunately, it isn’t helpful. It’s kind of like asking a store worker if something you’re looking for is on the aisle you’re in and they just say no. You want them to point you to the correct aisle. You want more information.

A 404 page should give you more information. It should be helpful. It should provide tools, links, advice, or some form of help. You don’t want to be left alone in the aisle not knowing where to go next.

Custom 404 Page Examples

There are thousands of amazing 404 pages across the web. Some are funny, some are serious. Some are more helpful than others. A few are plain, while others are gorgeous. Here’s a look at a few 404 pages to get an idea of how they’re designed. Some are simple and boring while others are helpful and look great.

1. Google

google

Google’s (not WordPress) 404 page is simple. It’s a small area of content in the center of the screen. The message just tells you there’s an error and provides a graphic of a robot in pieces. It doesn’t provide other information, but it’s Google, so all you have to do is type something else in the search bar.

2. WordPress.org

WordPress.org

WordPress.org’s 404 page displays their standard header and footer. The body includes a title to show the page wasn’t found, a short explanation with a touch of humor, and then a list of links to help guide you. The links focus on being helpful.

3. WordPress.com

WordPress.com

WordPress.com’s 404 page removes the header and footer. It shows a graphic, a title, a description with clickable links, a search box, and the WordPress.com logo. The links are helpful.

4. Elegant Themes

Elegant Themes

Elegant Themes’ 404 page (because I know you’re going to look anyway) shows the ET header, a large title with a small explanation, and a button as a CTA. You have access to almost everything from here.

5. Twenty Twenty-One

Twenty Twenty-One

WordPress’s Twenty Twenty-One theme has a 404 page that uses your primary and footer menus. It has a large title. The body has a short description and a search box. Lines are used for styling. The background matches the site.

6. Twenty Twenty

Twenty Twenty

WordPress’s Twenty Twenty theme displays the header and footer. The body shows a large title in the center, an explanation, and a search box. All use the theme’s colors.

7. Slack

Slack

Slack’s (non WordPress) 404 page shows a box in the center with information about the error with a link to the help center. All the menus are here, too. The interesting part is the background. It’s a cartoon background that scrolls right or left to follow your mouse. Animated animals move across the screen.

8. Amazon

Amazon

Amazon’s (also not WordPress) 404 page includes the Amazon logo with a search box, a large message, a smaller message with a link to the home page, and a photo of an animal with a link to learn more. It includes lots of different photos that can be displayed. They’re chosen at random.

404 Page Content

So, what does a 404 page need? We see a few common elements in the examples above.

First, it needs to be helpful. It shouldn’t just tell the visitor there is an error. It should tell what the error means. Imagine an error light coming on in your car. Your first question would be “what does that mean?” Not providing useful information about the error is frustrating.

Visitors need to know if they did something wrong or if the content doesn’t exist. If they don’t know, they’ll keep looking for the content until they furiously leave the website, vowing to never return. This is best done with a simple message and possibly an image that catches the eye. Something that stands out from your normal content that would appeal to your audience.

Next, it needs to provide some direction of what to do next. This could be a list of articles, a search box, a list of categories, most popular posts, most recent posts, a way to contact you, etc.

It’s that simple. 404 pages don’t need a lot of content. Just enough to be helpful.

The example above includes:

  • Background colors and patterns that would match the website/
  • A title with a short message about the error.
  • Large text showing that it’s a 404 page.
  • A few buttons providing the visitor with some directions.

It’s simple but stylish and helpful. That’s all you need.

Let’s look at how to create a custom 404 page for WordPress using the content ideas we just discussed.

How to Create a Custom 404 Page in WordPress with the Divi Theme Builder

404 Page Content

The Divi Theme Builder makes it easy to create and assign a 404 page. Elegant Themes has several premade 404 pages that you can download for free. You can customize them any way you want. They’re a great way to get a head start on a 404 page design. If you prefer, you can build one from scratch.

The example above is from the Fourth Theme Builder layout pack. There are lots of 404 pages available in the ET blog. To find them, search for “theme builder layout pack” or check them out here:

  • Download The First FREE Theme Builder Pack For Divi
  • Download The Second FREE Theme Builder Pack For Divi
  • Download The Third FREE Theme Builder Pack For Divi
  • Download the Fourth FREE Theme Builder Pack for Divi
  • Download the Fifth FREE Theme Builder Pack for Divi
  • Download the Sixth FREE Theme Builder Pack for Divi

Importing a Custom 404 Page into the Divi Theme Builder

Importing a Custom 404 Page into the Divi Theme Builder

You’ll find the Divi Theme Builder in the WordPress dashboard by going to Divi > Theme Builder. This opens the page where you can create or import templates and assign them. In the upper right corner, you’ll see the import icon. Click this icon to import your 404 page template.

Note – for tutorials on using the Divi Theme Builder, search for “theme builder” here in the Elegant Themes blog.

Importing a Custom 404 Page into the Divi Theme Builder

A modal opens where you can import your template. Select Import and navigate to your file under Choose File. The options to override the defaults and assignments are selected by default. I recommend leaving them selected. Click to import the template at the bottom of the modal. I’m importing the 404 page for the Crowdfunding Layout Pack.

Importing a Custom 404 Page into the Divi Theme Builder

By importing a 404 page, it’s assigned automatically. Next, click on the edit icon to open the builder.

Importing a Custom 404 Page into the Divi Theme Builder

Now, make your edits within each module by adding your links, images, colors, text, etc. Save the layout and click the x in the upper right corner to close the builder.

Importing a Custom 404 Page into the Divi Theme Builder

Finally, save the changes to apply the template. You now have a custom 404 page.

Creating a Custom 404 Page with the Divi Theme Builder

Importing a Custom 404 Page into the Divi Theme Builder

In the Theme Builder, select to add a new template.

This opens the template settings. Scroll to the bottom and select 404 Page under Other. Next, click Create Template. The template settings will close.

Creating a Custom 404 Page with the Divi Theme Builder

Now, you can create the 404 page. Most don’t use a header or footer. Select Add Custom Body.

Creating a Custom 404 Page with the Divi Theme Builder

This shows two selections allowing you to build a custom body or add from the library. Select Build Custom Body.

Creating a Custom 404 Page with the Divi Theme Builder

Build the 404 page with the Divi Builder as normal. Save and exit.

Creating a Custom 404 Page with the Divi Theme Builder

Finally, save your changes. You’re done.

Ending Thoughts on Creating a Custom 404 Page for WordPress

That’s our look at how to create a custom 404 page for WordPress. 404 pages need to be helpful. Unfortunately, the generic WordPress 404 page isn’t helpful, and it provides a poor user experience. Fortunately, you can create your own 404 page using the Divi Theme Builder.

Using the information we’ve provided here, you’re well on your way to create a beautiful 404 page that provides users with a great experience and looks amazing while doing it.

We want to hear from you. Have you created a custom 404 page for your WordPress website? Let us know about our experience in the comments.

Featured Image via Letters-Shmetters / shutterstock.com

An error 404 is when a visitor tries to access a page that does not exist. Sometimes people tend to overlook this feature, and never think about designing for it. Taking the time to make a user-friendly 404 page could mean the difference in a user staying on your website, or leaving.

Chances are you have created your website and checked multiple times to be sure that every link leads to somewhere. Eventually over time you may forget about a link that leads to a post you removed, or possibly changed the name to. Even if a visitor is searching for a page directly and they don’t get it right, then they will be taken to the error 404 page.

These can be made very user-friendly utilizing the WordPress template tags, and little bit of know-how.

Understanding The Error 404

The error 404 is a message that the visitor will receive when a page or post is not located. This is by default included within WordPress, but not with all themes. If you have created a custom theme, then you can increase the chances of a user sticking around even though they didn’t find what they were looking for with a properly designed 404 page.

The Basic Error 404 Template

The basic error 404 template is included with some WordPress themes but not all. WordPress is set to automatically look for the file 404.php when an error 404 is reached. If this file is not present, then it will give a basic error message which is not user-friendly.

If you do not already have this file you can create it. Make a new blank file and name it 404.php

Here is the basic code we will start with:

The 404.php File

<?php get_header(); ?>


<h2>Error 404 - Page Not Found.</h2>


<?php get_sidebar(); ?>

<?php get_footer(); ?>

The above code within the 404.php file would give a simple output wrapped in H2 tags that would read “Error 404 – Page Not Found.” – It would also get the WordPress Header, Sidebar, and Footer. These are all optional and should be modified to fit your WordPress theme.

We want to take this a few steps further to achieve our goal. Make a note that I am using the get_header() along with get_sidebar and footer to call our theme template files. Your’s may vary slightly and you will have to adjust your 404.php file accordingly.

Starting To Work On It

First, We will add the search form to our basic 404 page to make it a bit more helpful. This way even if a visitor lands on your 404, they then have the option of searching your site. This is the first method to help users stick around instead of leaving.

404.php File – Added Search Form

<?php get_header(); ?>

<h2>Error 404 - Page Not Found.</h2>

Search:

<?php include(TEMPLATEPATH . "/searchform.php"); ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Making It More Dynamic

To create a more dynamic error 404 page you can use redirects so that the user only sees the error briefly, then gets redirected to your home page. This page can be made to be somewhat SEO friendly as well.

For this next example we can start by editing the header.php file of your template. Within the meta tags at the top of your header.php file you can add the following:

The header.php File

<?php if (is_404()) { $redirectHome = get_option('home'); ?>
<?php echo $redirectHome; ?>

After this is added we will then edit our 404.php file to look like this:

404.php File

<?php get_header(); ?>

<h1>Error 404 - File Not Found.</h1>

<h3>Please <a href="<?php bloginfo('home'); ?>" Click here</a> to return to our home page, or you can wait to be redirected in 15 seconds.</h3>

<?php get_footer(); ?>

The above example will allow the user to land on the 404 error page but then automatically take them back to the home page. This will also help users stick around instead of them being left confused and leaving your website.

This example may not always be the best solution for everyone but can be helpful to someone looking for something specific on your site.

Making sure it works

You can test your 404 error page by typing your URL and following it with a page that you know does not exist.

Example: http://www.yourwebsitedomain.com/test404page.php

That should bring you to your 404 page for viewing and testing.

If it doesn’t work

If by chance your server is not automatically bringing you to your 404.php file we can modify our .htaccess file to make it work. Locate your .htaccess file within your WordPress install and add the following line to it:

ErrorDocument 404 /index.php?error=404

If your WordPress install is not in the root directory you will need to make sure the above code reflects that. If you have installed WordPress into a subfolder then modify your .htaccess like this:

ErrorDocument 404 /YOURSUBFOLDERNAME/index.php?error=404

This will force the use of your 404.php file.

A full example

The code below is a full demonstration that will show you some ways you can use the 404.php file to help users that have found something that doesn’t exist. Take a look at it and notice the options we are giving them to keep them around, and to help them find content.

<?php get_header(); ?>

<h1>404 Error</h1>

We cannot seem to find what you were looking for.

Maybe we can still help you.

<ul>

<li>You can search our site using the form provided below.</li>

<li>You can visit <a href="<?php bloginfo?>"</a></li>

<a href="<?php ('url'); ?>" the homepage.</a>

<li>Or you can view some of our recent posts.</li>

</ul>

Search:

TEMPLATEPATH . "/searchform.php"); ?>

<h3>Recent Posts</h3>

<ul>
	<?php query_posts('posts_per_page=5'); if (have_posts()) : while (have_posts()) : the_post(); ?>

<li><a href="<?php the_permalink() ?>" title="Permalink for : <?php the_title(); ?>"><?php the_title(); ?></a>
	endwhile; endif; ?>
	</ul>

<?php get_footer(); ?>

Anything above can be changed and styled to fit your needs. In the above example we are displaying that there was an error, and then following it with a list of options for the user. We are also still giving them the option to search our site, and have now added the ability for them to view our recent posts.

The combination of all of these gives the user that reached the page options. These options can be used to ensure a user doesn’t leave right away if they didn’t find exactly what they wanted.

Make it More User Friendly

To make it more user friendly and unique you could consider using the above examples with a different background image of your choice. You can also use html within the 404.php file to make a page all in itself for your error page. Here are some examples of unique error 404 pages for inspiration:

1. Mundofox.com

2. CSSRemix.com

3. CSSRemix.com

4. ChrisJennings.com

5. ook.co.uk

6. Youcastr.com

7. Mixx.com

8. JustCreativeDesign.com

9. Agens.no

10. Mushroomdigital.co.uk

Using it Wisely

It is always good practice for both WordPress and static HTML sites to make use of the 404 page. Either using ads on it to monetize, or using it to better help your visitors navigate your website.

There are many ways to create your own custom 404 error page, and just as many ways to allow it to help website visitors. Use the examples above freely, and experiment with what works best for you.

This post may contain affiliate links. See our disclosure about affiliate links here.

Понравилась статья? Поделить с друзьями:
  • Как настроить ошибку 404 на wordpress
  • Как настроить ошибку 404 html
  • Как настроить ошибка 404 на joomla
  • Как настроить общий доступ к принтеру если ошибка
  • Как настроить обработку 404 ошибки