Скрыть ошибки php wordpress

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

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

inet.ws - Powerful VPS around the World!

Как отключить вывод 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 around the World!
Алексей Шевченко

Изучает сайтостроение с 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 theme, plugin, or a custom 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 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.

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.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience building WordPress websites. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.

I know about error_reporting(0);, and ini_set('display_errors', false);, but there is a notice appearing in wordpress:

Notice: Array to string conversion in /var/www/vhosts/treethink.net/subdomains/parkridge/httpdocs/wp-includes/formatting.php on line 359

it only appears in wordpress, not in any other pages of the site.

I checked phpinfo(), and everything is set so that errors are not displayed. Why does this one still show up?

Here is the line that generates the error:

function wp_check_invalid_utf8( $string, $strip = false ) {
    $string = (string) $string;

I did change some thing in wordpress, to change how the gallery worked. But not this function, and I don’t think I changed any calls to this function either. Aside from the notice appearing, everything seems to operate perfectly fine, I just need to get this error to hide.

Скриншот ниже выглядит страшновато 🙂 , но именно с таким текстом вы случайно можете встретиться на страницах вашего сайта, если определенный плагин или иной код вызывает ошибки 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 по […]

Подробнее

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

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

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

Почему? Каждый из нас знает, что позитивные отзывы оставляют единицы, в первую очередь просто из-за лени 🙂 . А для […]

Подробнее

Are you trying to turn off PHP errors in WordPress?

The WordPress development environment has an easy-to-use debugging mode. It provides a warning message that indicates what file is the problem and what line it is located in.

Visitors, on the other hand, may find this unattractive and people can easily become discouraged by seeing this WordPress error message.

In this article, I’ll show you how to easily turn off PHP errors in WordPress.

If you need more help working out your WordPress Errors, you should also check my WordPress Error Logs Starter Guide.

Table of contents

  • PHP Error Messages: What Causes Them?
    • Turning off PHP Errors in WordPress

      PHP Error Messages: What Causes Them?

      Most of the time, PHP file 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.

      A theme or plugin can also generate PHP warnings when used with an incompatible component. There is a possibility that two current plugins that work well individually may not work well together. The reason for this is that everyone develops websites differently, hence there is no standard syntax for each web developer.

      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.

      Most PHP errors are not dangerous for your website, but some of them might break or slow it. That’s why it’s important to monitor them with a plugin like WP Umbrella.

      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

      Turning off PHP Errors in WordPress

      This part requires editing the wp-config.php file.

      It would be wise to make a backup of your site before making any changes to the wp-config.php file. If anything goes wrong, you’ll have a quick way of restoring the site.

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

      define('WP_DEBUG', true);

      Or

      define('WP_DEBUG', false);

      It is necessary to replace this line with the following code in either case:

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

      Save your changes, and then upload your wp-config.php file back to the server.

      The PHP errors, notices, and warnings on your website should now be gone.

      Thanks for reading this article on how to disable PHP errors, notices and warnings in WordPress, I hope it helped you!

      Agency or freelancer?

      Foster your WordPress Maintenance Business

      Get started

      Понравилась статья? Поделить с друзьями:
    • Скрытые ошибки программы
    • Скрытие приложения magisk ошибка
    • Скрытая тавтология примеры ошибок
    • Скручивания на полу ошибки
    • Скрутка проводов ошибки