WordPress скрыть ошибки

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

В этом уроке мы покажем, как можно скрыть и отключить отображение PHP ошибок на сайте WordPress.

inet.ws - Powerful VPS Hosting in the USA, Canada, UK and DE!

Как отключить вывод PHP ошибок в WordPress

Смотрите также:

  • WP Security Audit Log — следите за всеми изменениями на вашем сайте WordPress
  • WordPress Changelog — Как узнать, когда с вашим сайтом что-то пошло не так
  • WordPress File Monitor — узнайте, изменялись ли файлы на вашем сайте
  • Как уследить за действиями пользователей и изменениями на WordPress-сайте

Когда и зачем отключать ошибки PHP на WordPress?

PHP ошибки, которые вы можете видеть вверху страницы сайта, как правило являются предупреждениями или уведомлениями. Это далеко не то же самое, что Internal Server Error, Syntax Error или Fatal Error, которые останавливают ваш полностью.

Предупреждения и уведомления — это разновидность ошибок, которые не останавливают работу и загрузку WordPress. Читайте более подробно в нашей статье: WordPress под капотом: Порядок загрузки функций и файлов WordPress сайта.

Как отключить вывод PHP ошибок в WordPress

Цель этих предупреждений — дать подсказки разработчику при отладке кода. Разработчики плагинов и тем используют эту полезную информацию в попытках исключить все баги и ошибки в финальной версии.

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

Как отключить вывод PHP ошибок в WordPress

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

Давайте посмотрим, как это можно сделать на WordPress.

Как отключить показ PHP ошибок в WordPress

Для выполнения этой задачи нам потребуется отредактировать файл wp-config.php.

Внутри файла wp-config.php, который лежит в корне вашего сайта, найдите строчку кода:

define('WP_DEBUG', true);

Вполне возможно, что значение этого параметра у вас установлено на FALSE, в таком случае вы найдете строчку с кодом:

define('WP_DEBUG', false);

В любом случае, вам нужно заменить эту строчку на следующий код:

ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);

Не забудьте сохранить изменения и загрузить файл wp-config.php обратно на сайт.

Теперь вы можете зайти на свой сайт и убедиться, что все ошибки и предупреждения PHP исчезли.

Как включить показ PHP ошибок в WordPress

Если вы занимаетесь разработкой на локальном сервере или на тестовом сайте, тогда есть смысл поступить наоборот и принудительно включить показ всех PHP предупреждений и ошибок.

Для этого снова откройте файл wp-config.php и замените код, который мы приводили выше, на этот:

define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', true);

Этот код даст команду WordPress отображать все виды PHP ошибок, предупреждений и ошибок снова.

Источник: wpbeginner.com

Смотрите также:

inet.ws - Powerful VPS Hosting in the USA, Canada, UK and DE!
Алексей Шевченко

Изучает сайтостроение с 2008 года. Практикующий вебмастер, специализирующий на создание сайтов на WordPress. Задать вопрос Алексею можно на https://profiles.wordpress.org/wpthemeus/

Recently one of our readers asked how to turn off PHP errors in WordPress?

PHP warnings and notices help developers debug issues with their code. However, it looks extremely unprofessional when they are visible to all your website visitors.

In this article, we will show you how to easily turn off PHP errors in WordPress.

How to turn off PHP errors in WordPress

Why and When You Should Turn Off PHP Errors in WordPress?

PHP errors that you can see on your WordPress site are usually warnings and notices. These are not like internal server error, syntax errors, or fatal errors, which stop your website from loading.

Notices and warnings are the kind of errors that do not stop WordPress from loading your website. See how WordPress actually works behind the scenes for more details.

PHP errors in WordPress admin area

The purpose of these errors are to help developers debug issues with their code. Plugin and theme developers need this information to check for compatibility and best practices.

However, if you are not developing a custom theme, plugin, or website, then these errors should be hidden. Because if they appear on the front-end of your website to all your visitors, it looks extremely unprofessional.

WordPress warning errors on homepage

If you see an error like above on on your WordPress site, then you may want to inform the respective theme or plugin developer. They may release a fix that would make the error go away. Meanwhile, you can also turn these errors off.

Let’s take a look at how to easily turn off PHP errors, notices, and warnings in WordPress.

Turning off PHP Errors in WordPress

For this part, you will need to edit the wp-config.php file.

Inside your wp-config.php file, look for the following line:

define('WP_DEBUG', true);

It is also possible, that this line is already set to false. In that case, you’ll see the following code:

define('WP_DEBUG', false);

In either case, you need to replace this line with the following code:

ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);

Don’t forget to save your changes and upload your wp-config.php file back to the server.

You can now visit your website to confirm that the PHP errors, notices, and warnings have disappeared from your website.

Turning on PHP Errors in WordPress

If you are working on a website on local server or staging area, then you may want to turn on error reporting. In that case you need to edit your wp-config.php file and replace the code you added earlier with the following code:

define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', true);

This code will allow WordPress to start displaying PHP errors, warnings, and notices again.

We hope this article helped you learn how to turn off PHP errors in WordPress. You may also want to see our list of the most common WordPress errors and how to fix them, or our expert picks of the best web design software.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here’s our editorial process.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Reader Interactions

Скриншот ниже выглядит страшновато 🙂 , но именно с таким текстом вы случайно можете встретиться на страницах вашего сайта, если определенный плагин или иной код вызывает ошибки PHP. С другой стороны, именно этот код будет вам полезен в процессе поиска проблемы.

В первую очередь, следует понимать, что ошибки бывают разной степени “критичности”. Чаще всего вы встретите так называемые предупреждения “Warnings“, а также фатальные ошибки “Fatal errors“.

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

Во втором случае вы можете просто видеть белый экран вместо какой-то из страниц.

Как отключить вывод ошибок

Следующий код выключает вывод ошибок на страницах сайта. Его необходимо добавить в файл wp-config.php, находящийся в корне вашего сайта. Проще всего найти в этом файле текст define ( 'WP_DEBUG ", false); и вместо него добавить:

error_reporting(0); // выключаем вывод информации об ошибках
ini_set('display_errors', 0); // выключаем вывод информации об ошибках на экран
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false); 

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

Как включить вывод ошибок?

Следующий код наоборот включает вывод ошибок, что позволит вам или вашему вебмастеру скорее и проще узнать о причинах проблем на сайте, очень помогает, когда вместо страницы сайта показывается просто белая страница без данных:

error_reporting(E_ALL); // включаем вывод ошибок
ini_set('display_errors', 1); // включаем вывод ошибок на экран
define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', true);

Разместить этот код необходимо один в один как и предыдущий в файле wp-config.php

Плагины для поиска ошибок в WordPress (дебаг и профилирование)

Для WordPress есть несколько замечательных плагинов, которые позволят более глубоко погрузиться в процесс поиска ошибок и их причин. Вот несколько популярных из них:

  • Query Monitor – выводит в футере довольно много полезной информации, в частности о запросах, выполненных во время генерации текущей страницы. Среди всей выводимой информации приведены время генерации страницы, сколько было SQL запросов, какие именно и время их выполнения, сколько памяти потрачено, какие хуки использованы и другое.
  • Debug Bar – набор плагинов для дебага. Это основной плагин, к которому можно подключать дополнительные, расширяющие функциональность основного.
  • Log Deprecated Notices – записывает информацию о наличии устаревших функций в WordPress или их параметров, работа плагина не зависит от значений константы WP_DEBUG, то есть работает всегда.
  • WordPress mu-plugin for debugging – альтернативный плагин на базе библиотеки Kint.
  • Clockwork для WordPress – интересный плагин для отладки через консоль браузеров Google Chrome или Firefox, есть возможность отладки AJAX-запросов.

Еще интересное:

Акции, скидки на хостинг и домены

Скидка на домены .CITY

Скидка на домены .CITY

Новое акционное предложение уже доступно для вас – скидка 70% на регистрацию домена .CITY Только до конца июня покупайте #домен #city по цене 300грн , используйте промокод city300 в процессе заказа, скидка применится на последнем шаге заказа! Прекрасный выбор для любых доменов, связанных с городами, городскими властями или организациями, которые представляют свой город в том или ином амплуа. Домен можно купить тут https://wphost.me/ru/domains/ Мы оставляем […]

Подробнее

Акции, скидки на хостинг и домены

Подарки за отзывы

Подарки за отзывы

Почему? Каждый из нас знает, что позитивные отзывы оставляют единицы, в первую очередь просто из-за лени 🙂 . А для собственников бизнеса, работников, людей, которые ежедневно выкладываются, чтобы предоставить услугу качественно – позитивные отзывы это наилучшая мотивация! Мы регулярно получаем в запросах в техподдержку слова благодарности за ту или иную помощь, часто даже сделанную вне компетенции наших специалистов. Но все […]

Подробнее

From time to time a user comes to me and says “I see some PHP notices and warnings on my page”.

Most of the time these are nothing to worry about (though the plugin/theme developer should know about these so that they may fix them in a future release).
PHP warnings and notices are nothing to worry about on a production site most of the time.
Some of these can even be generated because the developer has to keep compatibility with older versions of WordPress as well as older PHP versions.

The solution:

If you simply set WP_DEBUG to false in your wp-config.php file you should be fine. These don’t affect your site in any way.

However, the problem is that some times the above does not work.
That can happen most times on cheap shared hosts that force displaying PHP warnings and notices.
In that case, you can replace this line from your wp-config.php file:

define('WP_DEBUG', false);

with this:

ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);

I hope that helps someone out there!

Are you trying to turn off warnings or PHP errors in WordPress? Such warnings and errors are unappealing and can also turn away visitors, so it’s important to learn how to hide them.

In this guide, we’ll explain you how to hide warnings and disable PHP errors in WordPress.

Understanding PHP Errors and Warnings in WordPress

PHP errors and warnings are messages generated by the server and giving information about an issue in the PHP code of your WordPress website.

PHP errors usually point to a more serious issue, like a critical problem in your code that could break your website.

Warnings are more like a friendly nudge; they alert you to potential problems but don’t stop the script from running.

These messages can be invaluable for developers during debugging. If you want to learn more about PHP errors, the official documentation of PHP is a must have.

PHP Error Messages: What Causes Them?

Most of the time, PHP warnings occur due to outdated plugins or themes. The reason is that core files are frequently updated with WordPress updates, so some code becomes obsolete or deprecated.

Incompatibility between plugins or between a plugin and your active theme can also be responsible for the error. The lack of a standardized coding syntax among developers and plugin editors adds to this complexity.

Fortunately, these warnings don’t necessarily indicate that the site is broken. It just looks ugly to a visitor who doesn’t expect it. An update may be created by the developer to remove the warning, but it isn’t always instantaneous.

They usually don’t mean your website is broken, but they can make it look unprofessional. Monitoring them with a plugin like WP Umbrella can help you catch issues before they escalate.

PHP warnings in WordPress look something like this: “/wp-content/plugins/pluginfile.php on line 238”

Basically, it just means a part of the file is incompatible with WordPress, the theme, or another plugin that you are using.

Until you fix the coding yourself, it might be best to simply disable the warning messages entirely

How to Hide Warnings and Disable PHP Errors in WordPress

This part requires editing the wp-config.php file. Before diving into the technical part, ensure you backup your website. A backup will provide you with a safety net in case things go south.

Step 1. Open Your wp-config.php File

Look in your wp-config.php file for the following line:

define('WP_DEBUG', true);

Or

define('WP_DEBUG', false);

Step 2. Replace the Debug Lines

Replace the existing lines with the following code snippet:

ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);

Step 3. Save and Upload

Save your changes and re-upload your wp-config.php file back to your web server. You should no longer see PHP errors, notices, or warnings on your website.

Need Additional Help With Errors and Warnings?

If you encounter any issues or have more questions, you can always contact the plugin’s developer or seek advice in the WordPress support forums.

You can also rename your plugins folder via FTP to something like plugins_debug for further testing.

Remember to keep your WordPress plugins, themes, and core up-to-date. Also, make sure you’re running the latest version of PHP to avoid any compatibility issues.

Понравилась статья? Поделить с друзьями:
  • Wot blitz ошибка 65 на компьютер
  • Wordpress сайт ошибка 500
  • Wordpress плагин если нашли ошибку
  • Wordpress пагинация 404 ошибка
  • Wot blitz ошибка 0x00000000