WordPress вывод ошибок на экран

Темы

  • WP_DEBUG
    • PHP ошибки, предупреждения, и заметки
    • Устаревшие функции и аргументы
  • WP_DEBUG_LOG
  • WP_DEBUG_DISPLAY
  • SCRIPT_DEBUG
  • SAVEQUERIES
  • Пример файла wp-config.php для отладки
  • Плагины для отладки
  • Внешние ссылки

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

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

WP_DEBUG

WP_DEBUG это константа PHP , используемая для установки режима отладки в WordPress. По умолчанию она имеет значение «false», но может быть установлена как «true» в файле конфигурации wp-config.php на сайтах, на которых проводится отладка.

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

Заметка: значения true и false в примере не заключены в кавычки или апострофы, поскольку являются булевыми (правда/ложь) значениями. Не заключайте их в кавычки (например 'false'), иначе они станут восприниматься как строковые значения.

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

Наверх ↑

PHP ошибки, предупреждения, и заметки

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

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

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

Наверх ↑

Устаревшие функции и аргументы

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

Наверх ↑

WP_DEBUG_LOG

WP_DEBUG_LOG это дополнение к WP_DEBUG которое позволяет сохранять ошибки в файл debug.log. Это полезно если вы хотите посмотреть ошибки позже или посмотреть то, что не выводится на экран (например для AJAX запросов или работы wp-cron).

Заметьте, что запись в лог производится внутренней функцией PHP error_log(), она очень удобна для отладки событий AJAX.

При установке в значение true, журнал будет сохраняться как wp-content/debug.log на вашем сайте. Вы можете задать альтернативное имя, для сохранения его в другом месте.

define( 'WP_DEBUG_LOG', true );
-или-
define( 'WP_DEBUG_LOG', '/tmp/wp-errors.log' );

Заметка: Для работы WP_DEBUG_LOG нужно включить WP_DEBUG (true). Вы можете независимо от этого отключить WP_DEBUG_DISPLAY.

Наверх ↑

WP_DEBUG_DISPLAY

WP_DEBUG_DISPLAY это другое дополнение для WP_DEBUG, которое контролирует вывод сообщений отладки в HTML код страницы (на экран). Значение по умолчанию — ‘true’, что позволяет видеть ошибки и предупреждения на экране, в момент их возникновения. Установка значения как false спрячет все ошибки, что можно использовать вместе с WP_DEBUG_LOG, чтобы просмотреть ошибки из файла позже.

define( 'WP_DEBUG_DISPLAY', false );

Заметка: Для работы WP_DEBUG_LOG нужно включить WP_DEBUG (true). Вы можете независимо от этого использовать WP_DEBUG_LOG

Наверх ↑

SCRIPT_DEBUG

SCRIPT_DEBUG это константа, позволяющая использовать версии для разработки CSS и JavaScript файлов ядра, вместо их оптимизированных версий, которые используются по умолчанию. Константа полезна при тестировани изменений в стандартных файлах .js и .css. По умолчанию — false.

define( 'SCRIPT_DEBUG', true );

Наверх ↑

SAVEQUERIES

Определение SAVEQUERIES будет сохранять запросы к СУБД в массив, который можно проанализировать. При определении константы как true, будут сохраняться все запросы, время исполнения, функция вызова запроса.

define( 'SAVEQUERIES', true );

Массив сохраняется в глобальном $wpdb->queries.

Заметка: Это сильно снижает производительность вашего сайта.

Наверх ↑

Пример файла wp-config.php для отладки

Следующий код в файле wp-config.php включит запись всех ошибок, предупреждений и заметок PHP в файл debug.log внутри папки wp-content. Он также отключит вывод на экран (в код страницы):

// Включить отладку WP_DEBUG
define( 'WP_DEBUG', true );

// Включить журнал /wp-content/debug.log
define( 'WP_DEBUG_LOG', true );

// Отключить вывод на экран
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Использовать версии JS и CSS для разработчика (при тестировании изменений в них)
define( 'SCRIPT_DEBUG', true );

Заметка: Это нужно вставить перед /* Это всё, дальше не редактируем. Успехов! */ в файл wp-config.php .

Наверх ↑

Плагины для отладки

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

  • Query Monitor
  • Debug Bar
  • Log Deprecated Notices

Наверх ↑

Внешние ссылки

  • Генератор файла «wp-config.php»
  • Плагин «No White Screen»: показывает ошибку вместо белого экрана

В разработке нужно иметь возможность смотреть где ошибка, когда что-то вдруг сломалось. В WordPress для этого есть специальный режим «дебаг» (режим отладки). В этой заметке разберем его на части и посмотрим что это за константа такая WP_DEBUG.

Зачем нужен «дебаг режим»?

Допустим, вы изменили код файла functions.php темы и сайт перестал работать. Вместо него белый экран — ничего не понятно. «дебаг» поможет разобраться, он покажет ошибку и скажет в какой она строке какого файла.

«Дебаг» выводит не только ошибки, из-за которых сайт перестает работать, но и заметки. Заметки могут создаваться самим PHP (например, когда неправильно используется переменная) или кодом PHP скрипта (например, WP создает такие заметки, если сайт использует устаревшую функцию WordPress, или устаревший параметр функции).

Читайте также

  • пример исправления скорости загрузки сайта через профилирование слабых мест с помощью xDebug + phpStorm.

  • Profiling WordPress Sites (видео)

Есть два варианта режима «дебаг»:

  1. WP_DEBUG_DISPLAY — Константа показа ошибок на экран.
  2. WP_DEBUG_LOG — Константа запись ошибок в лог файл.

Сам «дебаг» режим включается константой WP_DEBUG.

Все три константы могут принимать значения true или false.

По умолчанию константы дебага имеют такие значения:

  • WP_DEBUG = false (true при 'development' === wp_get_environment_type())
  • WP_DEBUG_DISPLAY = true
  • WP_DEBUG_LOG = false

Константы обычно определяются в файле wp-config.php.

wp_initial_constants() определяет дефолтные значения констнат, если они не установлены вручную. Функция срабатывает на раннем этапе загрузки WordPress.

wp_debug_mode() устанавливает настройки PHP на основе установленных констант.

WP_DEBUG_DISPLAY и WP_DEBUG_LOG активируются, только если включена константа WP_DEBUG.

Включение WP_DEBUG не изменяет значение других констант. Т.е. при WP_DEBUG=true WP_DEBUG_DISPLAY и WP_DEBUG_LOG сохранят свои дефолтные значения и на основе этих значений будут выставлены PHP настройки показа и логирования ошибок.

Отображение ошибок форсировано отключено для AJAX/REST/XMLRPC/JSONP запросов. См. код wp_debug_mode():

if (
	defined( 'XMLRPC_REQUEST' )
	|| defined( 'REST_REQUEST' )
	|| defined( 'MS_FILES_REQUEST' )
	|| ( defined( 'WP_INSTALLING' ) && WP_INSTALLING )
	|| wp_doing_ajax()
	|| wp_is_json_request()
) {
	ini_set( 'display_errors', 0 );
}

Как включить показ ошибок в AJAX запросе, сморите в статье про AJAX.

Важно отключать «дебаг» на рабочем сайте.

Как включить «дебаг» (показ ошибок в WordPress)

Базовое включение

Откройте файл wp-config.php в корне сайта и измените false на true в строке:

define( 'WP_DEBUG', true ); // false - отключить показ ошибок

При таком включении ошибки и заметки будут выводиться на экран, но ничего логироваться не будет.

Включение и настройка дебага

Код ниже, включит запись ошибок, предупреждений и заметок в файл wp-content/debug.log и выключит показ заметок и предупреждений на экране, чтобы они не мешались при просмотре сайта.

define( 'WP_DEBUG', true );     // включение дебаг режима
define( 'WP_DEBUG_LOG', true ); // true - логирование ошибок в файл /wp-content/debug.log
define( 'WP_DEBUG_DISPLAY', false ); // false - отключает показ ошибок на экране
define( 'SCRIPT_DEBUG', true ); // используем полные версии JS и CSS файлов движка

Вставлять этот код нужно в файл wp-config.php куда угодно, но до строки:

require_once( ABSPATH . 'wp-settings.php' );

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

error_log( $value );               // Скалярные величины
error_log( print_r( $value, 1) );  // Любые данные

Динамическое включение показа ошибок

Этот код помогает быстро включать константу WP_DEBUG, которая на рабочем сайте должна быть выключена. Также код позволяет включить запись ошибок в файл debug.log в папку /wp-content и отключить показ ошибок на экране.

Зачем это надо? Допустим, мы сделали сайт и на боевом сайте нам иногда нужно видеть ошибки (обычно конечно все это тестируется на локалке, но всякое бывает нужно). Чтобы видеть причину ошибки, нам нужно включить дебаг, но на боевом сайте где ходят пользователи делать этого не рекомендуется. С помощью кода ниже можно включить дебаг режим в WordPress через URL, зная определенный ключ.

Включение ошибок сохраняется в куку.

Установка

Замените строку define( WP_DEBUG, false ); в файле wp-config.php на такой код:

GitHub

<?php

/**
 * Dynamically enable/disable the display of PHP errors in WordPress.
 *
 * Installation:
 * replace line 'define( WP_DEBUG, false );' in 'wp-config.php' file with this code.
 *
 * Enabling debug mode:
 * NOTE: Strongly recommended to changing the 'debug' word to something more unique!
 * add the 'debug' query parameter to the URL. Examples:
 * https://site.com/?debug - default enabling of WP_DEBUG constant
 * https://site.com/?debug=1 - logging of errors into file 'DOCUMENT_ROOT/../php-errors-{HOST}.log'.
 * https://site.com/?debug=2 - linking uncompressed scripts and saving all SQL queries to $wpdb->queries
 * https://site.com/?debug=3 - saving all SQL queries in $wpdb->queries
 * https://site.com/?debug=4 - disable displaying errors (enabled by default)
 * https://site.com/?debug=14 - combining
 *
 * Disabling debug mode:
 * https://site.com/?debug=anything
 *
 * @author Kama (http://wp-kama.ru)
 * ver 2.5
 */
// IMPORTANT: change from `debug` to your unique key!
kama_define_wp_debug( 'debug' );

function kama_define_wp_debug( $key ){

	$val = isset( $_GET[ $key ] ) ? ( $_GET[ $key ] ?: 'yes' ) : false;

	// set/delete cookie
	if( $val !== false ){

		$cookie = preg_match( '/^(yes|[1234])$/', $val ) ? $val : null;

		$host = str_replace( 'www.', '', $_SERVER['HTTP_HOST'] );

		// cirilic domains: .сайт, .онлайн, .дети, .ком, .орг, .рус, .укр, .москва, .испытание, .бг
		false !== strpos( $host, 'xn--' )
			? preg_match( '~xn--[^.]+.xn--[^.]+$~', $host, $mm )
			: preg_match( '~[a-z0-9][a-z0-9-]{1,63}.[a-z.]{2,6}$~', $host, $mm );

		$host = $mm[0];

		$_COOKIE[ $key ] = $cookie;
		setcookie( $key, $cookie, time() + ( $cookie ? 3600 * 24 * 365 : -3600 ), '/', ".$host" );
	}

	// enable the debug based on the cookie
	if( ! empty( $_COOKIE[ $key ] ) ){

		define( 'WP_DEBUG', true );

		$set = array_flip(
			preg_split( '/(d)/', $_COOKIE[ $key ], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY )
		);

		isset( $set[1] ) && define( 'WP_DEBUG_LOG', dirname( $_SERVER['DOCUMENT_ROOT'] ) . "/php-errors-{$_SERVER['HTTP_HOST']}.log" );
		isset( $set[2] ) && define( 'SCRIPT_DEBUG', true );
		isset( $set[3] ) && define( 'SAVEQUERIES', true );
		isset( $set[4] ) && define( 'WP_DEBUG_DISPLAY', false );
	}
	else {
		define( 'WP_DEBUG', false );
	}
}

Теперь, чтобы включить режим WP_DEBUG, нужно добавить в любой URL сайта параметр запроса debug: http://example.com/?debug или http://example.com/?debug=1 (принудительный вывод на экран, если такой вывод отключен) или http://example.com/?debug=2 (логирование в файл).

Для защиты, ключ debug нужно изменить на свой, который будете знать только вы, потому что по нему вы будете включить/отключать дебаг режим.

При включении логирования, не забывайте удалять лог файл, а то его может посмотреть кто угодно. Или путь до файла лога можно изменить см. описание WP_DEBUG_LOG.

WP_DEBUG

WP_DEBUG — это PHP константа (глобальная постоянная — определяется всего один раз). Значение этой постоянной включает или отключает показ ошибок в PHP, а также она используется в разных местах кода WordPress для показа или подавления ошибок, где это необходимо.

WP_DEBUG нужно определять (устанавливать) в файле wp-config.php из корня сайта.

define( 'WP_DEBUG', false ); // дебаг отключен. По умолчанию.
// или
define( 'WP_DEBUG', true ); // дебаг включен

Для удобности, можно писать числа 1 или 0:

define( 'WP_DEBUG', 0 ); // дебаг отключен. По умолчанию.
// или
define( 'WP_DEBUG', 1 ); // дебаг включен

Заметка: нельзя указывать false в кавычках — ‘false’. В этом случае дебаг будет включен, потому что значение равно строке false, а не логическому — нет.

PHP ошибки, предупреждения и заметки (errors, warnings и notices)

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

  1. errors — серьезная ошибка, которая приводит к остановке скрипта. PHP прерывает работу.
  2. warnings — не ошибка, а предупреждение о чем-либо. PHP не прерывает работу.
  3. notices — не ошибка, а заметка о чем-либо. PHP не прерывает работу. Заметки могут показать возможные баги в коде. Их исправление, как правило, делает код более стабильным.

«Режим дебаг» включает все уровни ошибок. Это не похоже на обычное поведение PHP, там обычно включены только ошибки уровня errors, а warnings и notices не отображаются. Подробнее читайте в описании error_reporting().

Устаревшие функции, хуки и устаревшие параметры функций

WP_DEBUG также включает внутренние заметки самого WordPress. В WordPress есть специальные функции вроде _deprecated_function(), которые показывают ошибку уровня notices, когда используется устаревшая функция или хук или параметр хука, функции и т.д. Эти заметки предупреждают, что функция WP считается устаревшей и её нужно заменить, потому что она в любой момент может быть удалена. В таких заметках чаще всего предлагается альтернативная функция для замены.

WP_DEBUG_DISPLAY

По умолчанию: true.

Еще один компонент WP_DEBUG, который контролирует вывод (показ) ошибок на экран.

Зависит от WP_DEBUG! Работает только, если дебаг включен WP_DEBUG = true . В противном случае просто используется глобальное значение PHP опции display_errors.

Если указать в wp-config.php:

  • define( 'WP_DEBUG_DISPLAY', true ) — (по умолчанию) WP будет выводить (показывать) ошибки на экран.
  • define( 'WP_DEBUG_DISPLAY', false ) — ошибки не будут выводиться на экран. Это нужно, когда ошибки записываются в файл (см. WP_DEBUG_LOG) и их можно смотреть позднее.
  • define( 'WP_DEBUG_DISPLAY', null ) — WP вообще не будет указывать значение для PHP опции display_errors, т.е. будет использована глобальная настройка PHP (сервера).

Показ ошибок всегда отключается для REST, AJAX или XML-RPC запросов. Для них срабатывает такой код ini_set( ‘display_errors’, 0 ), но при этом значение константы WP_DEBUG_DISPLAY не изменяется!

WP_DEBUG_LOG

По умолчанию: false

Еще один компонент дебага. Включает запись ошибок в файл /wp-content/debug.log. Зависит от WP_DEBUG — работает только если WP_DEBUG равен true.

Запись ошибок в файл может пригодится, когда нужно проверить наличие ошибок в коде, который ничего не выводит на экран. Например, при AJAX запросе или при тестировании CRON или REST.

define( 'WP_DEBUG_LOG', true ); // true - запись ошибок в файл /wp-content/debug.log

Изменение адреса файла лога ошибок

Через WP

C WordPress 5.1, в WP_DEBUG_LOG можно указать путь к файлу лога:

define( 'WP_DEBUG_LOG', '/srv/path/to/custom/log/location/errors.log' );
Через PHP

Чтобы изменить название файла, добавьте следующую строку как можно раньше, например в MU плагины:

ini_set( 'error_log', WP_CONTENT_DIR . '/hidden-debug.log' );

Но эту строку нельзя добавлять в wp-config.php — это слишком рано…

Имейте ввиду:

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

SAVEQUERIES

По умолчанию: не определена.

Связанная с дебагом константана. При включении, все SQL запросы будут сохраняться в переменную $wpdb->queries в виде массива. В этом массиве можно будет посмотреть все SQL запросы и при необходимости найти нужный и убедиться что он правильный и т.п.

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

define( 'SAVEQUERIES', true ); // true - сохраняет SQL запросы и данные о них в  `$wpdb->queries`

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

SCRIPT_DEBUG

По умолчанию: false.

Связанная с дебагом константа. Контролирует какие JS и CSS файлы использовать: сжатые или полные. При включении WordPress будет использовать не сжатые версии (dev версии) JS и CSS файлов. По умолчанию используются min версии файлов. Это нужно для тестирования при изменении встроенных js или css файлов.

define( 'SCRIPT_DEBUG', true ); // true - использование полных версий `.css` и `.js` файлов

Как работает WP_DEBUG?

После установки констант дебага в wp-config.php мы заходим на сайт. И при генерации страницы, в самом начале загрузки WordPress (см. wp-settings.php) срабатывает функция wp_debug_mode(). Она, используя функции PHP, устанавливает как и какие уровни ошибок показывать, нужно ли создавать лог файл и т.д.

Не работает WP_DEBUG?

Иногда может возникнуть такая ситуация, когда вы включаете WP_DEBUG в конфиге, а ошибки все равно не видно. Такое поведение может возникнуть, когда где-то после установок параметров показа ошибок самим WordPress эти установки меняются. Например в MU плагине, обычном плагине или в теме, ошибки выключаются переустановкой ini директив PHP, примерно таким кодом:

error_reporting(0); // отключает сообщения об ошибках
ini_set('display_errors', 0); // отключает показ ошибок на экран

В этом случает установки дебага WP перебиваются и он перестает работать…

Для решения, лучше всего найти где изменяются настройки и удалить такие строки, чтобы дальше работать только с константой WP_DEBUG.

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

error_reporting(E_ALL); // включаем сообщения об ошибках
ini_set('display_errors', 1); // включаем показ ошибок на экран

Функции WP для дебага

  • wp_debug_backtrace_summary() — Получает трассировку с названиями функций — список названий всех функций/методов, которые были вызваны для того, чтобы добраться до текущего места в коде (откуда была вызвана эта функция).
  • wp_get_environment_type() — Получает текущий тип окружения: local, development, staging, production (по умолчанию).

Данные системы

Для дебага в WP есть класс WP_Debug_Data. Например, используя следующий метод мы можем получить кучу данных о системе:

require_once ABSPATH . '/wp-admin/includes/class-wp-debug-data.php';
require_once ABSPATH . '/wp-admin/includes/update.php';
require_once ABSPATH . '/wp-admin/includes/misc.php';

$data = WP_Debug_Data::debug_data();

print_r( $data );

Получим большой массив данных:

Array
(
	[wp-core] => Array
		(
			[label] => WordPress
			[fields] => Array
				(
					[version] => array( data )

					[site_language] => array( data )

					[user_language] => array( data )

					[timezone] => array( data )

					[home_url] => array( data )

					[site_url] => array( data )

					[permalink] => array( data )

					[https_status] => array( data )

					[multisite] => array( data )

					[user_registration] => array( data )

					[blog_public] => array( data )

					[default_comment_status] => array( data )

					[environment_type] => array( data )

					[user_count] => array( data )

					[dotorg_communication] => array( data )

				)

		)

	[wp-paths-sizes] => Array
		(
			[label] => Directories and Sizes
			[fields] => Array
				(
					[wordpress_path] => array( data )

					[wordpress_size] => array( data )

					[uploads_path] => array( data )

					[uploads_size] => array( data )

					[themes_path] => array( data )

					[themes_size] => array( data )

					[plugins_path] => array( data )

					[plugins_size] => array( data )

					[database_size] => array( data )

					[total_size] => array( data )

				)

		)

	[wp-dropins] => Array
		(
			[label] => Drop-ins
			[show_count] => 1
			[description] => Drop-ins are single files, found in the /public_html/assets directory, that replace or enhance WordPress features in ways that are not possible for traditional plugins.
			[fields] => Array
				(
					[maintenance.php] => array( data )

					[object-cache.php] => array( data )

				)

		)

	[wp-active-theme] => Array
		(
			[label] => Active Theme
			[fields] => Array
				(
					[name] => array( data )

					[version] => array( data )

					[author] => array( data )

					[author_website] => array( data )

					[parent_theme] => array( data )

					[theme_features] => array( data )

					[theme_path] => array( data )

					[auto_update] => array( data )

				)

		)

	[wp-parent-theme] => Array
		(
			[label] => Parent Theme
			[fields] => Array( data )
		)

	[wp-themes-inactive] => Array
		(
			[label] => Inactive Themes
			[show_count] => 1
			[fields] => Array
				(
					[Dummy] => array( data )

				)

		)

	[wp-mu-plugins] => Array
		(
			[label] => Must Use Plugins
			[show_count] => 1
			[fields] => Array
				(
					[disable-plugins-in-front.php] => array( data )

					[main.php] => array( data )

					[not_support_browsers_redirect.php] => array( data )

					[POMOdoro Translation Cache] => array( data )

					[protect-malicious-queries.php] => array( data )

					[Rus to Lat] => array( data )

				)

		)

	[wp-plugins-active] => Array
		(
			[label] => Active Plugins
			[show_count] => 1
			[fields] => Array
				(
					[AJAX Simply] => array( data )

					[Democracy Poll] => array( data )

					[Disable Emojis (GDPR friendly)] => array( data )

					[Display Active Plugins First] => array( data )

					[Kama Breadcrumbs] => array( data )

					[Kama Postviews] => array( data )

					[Kama SpamBlock] => array( data )

					[Kama Thumbnail Pro] => array( data )

					[Redis Object Cache] => array( data )

				)

		)

	[wp-plugins-inactive] => Array
		(
			[label] => Inactive Plugins
			[show_count] => 1
			[fields] => Array
				(
					[404 Error Monitor] => array( data )

					[Category Order and Taxonomy Terms Order] => array( data )

					[Contact Form 7] => array( data )

					[Kama Thumbnail] => array( data )

					[Query Monitor] => array( data )

					[Query Monitor Extend] => array( data )

					[Right Now Reloaded] => array( data )

					[Three Column Screen Layout] => array( data )

					[TinyPNG - JPEG, PNG & WebP image compression] => array( data )

					[User Role Editor] => array( data )

					[Widget Logic] => array( data )

					[WooCommerce] => array( data )

					[WordPress Sphinx Search Plugin] => array( data )

					[WP Crontrol] => array( data )

					[WP Super Cache] => array( data )

					[Yoast SEO] => array( data )

				)

		)

	[wp-media] => Array
		(
			[label] => Media Handling
			[fields] => Array
				(
					[image_editor] => array( data )

					[imagick_module_version] => array( data )

					[imagemagick_version] => array( data )

					[imagick_version] => array( data )

					[file_uploads] => array( data )

					[post_max_size] => array( data )

					[upload_max_filesize] => array( data )

					[max_effective_size] => array( data )

					[max_file_uploads] => array( data )

					[imagick_limits] => Array ( data )

					[imagemagick_file_formats] => Array( JPEG, JPG, MOV, MP4, MPEG, MPG, PNG, PNG24, WBMP, WEBP, WMV ... )

					[gd_version] => array( data )

					[gd_formats] => array( data )

					[ghostscript_version] => array( data )

				)

		)

	[wp-server] => Array
		(
			[label] => Server
			[description] => The options shown below relate to your server setup. If changes are required, you may need your web host’s assistance.
			[fields] => Array
				(
					[server_architecture] => array( data )

					[httpd_software] => array( data )

					[php_version] => array( data )

					[php_sapi] => array( data )

					[max_input_variables] => array( data )

					[time_limit] => array( data )

					[memory_limit] => array( data )

					[max_input_time] => array( data )

					[upload_max_filesize] => array( data )

					[php_post_max_size] => array( data )

					[curl_version] => array( data )

					[suhosin] => array( data )

					[imagick_availability] => array( data )

					[pretty_permalinks] => array( data )

				)

		)

	[wp-database] => Array
		(
			[label] => Database
			[fields] => Array
				(
					[extension] => array( data )

					[server_version] => array( data )

					[client_version] => array( data )

					[database_user] => array( data )

					[database_host] => array( data )

					[database_name] => array( data )

					[database_prefix] => array( data )

					[database_charset] => array( data )

					[database_collate] => array( data )

				)

		)

	[wp-constants] => Array
		(
			[label] => WordPress Constants
			[description] => These settings alter where and how parts of WordPress are loaded.
			[fields] => Array
				(
					[ABSPATH] => array( data )

					[WP_HOME] => array( data )

					[WP_SITEURL] => array( data )

					[WP_CONTENT_DIR] => array( data )

					[WP_PLUGIN_DIR] => array( data )

					[WP_MEMORY_LIMIT] => array( data )

					[WP_MAX_MEMORY_LIMIT] => array( data )

					[WP_DEBUG] => array( data )

					[WP_DEBUG_DISPLAY] => array( data )

					[WP_DEBUG_LOG] => array( data )

					[SCRIPT_DEBUG] => array( data )

					[WP_CACHE] => array( data )

					[CONCATENATE_SCRIPTS] => array( data )

					[COMPRESS_SCRIPTS] => array( data )

					[COMPRESS_CSS] => array( data )

					[WP_LOCAL_DEV] => array( data )

					[DB_CHARSET] => array( data )

					[DB_COLLATE] => Array
						(
						)

				)

		)

	[wp-filesystem] => Array
		(
			[label] => Filesystem Permissions
			[description] => Shows whether WordPress is able to write to the directories it needs access to.
			[fields] => Array
				(
					[wordpress] => array( data )

					[wp-content] => array( data )

					[uploads] => array( data )

					[plugins] => array( data )

					[themes] => array( data )

					[mu-plugins] => array( data )

				)

		)

)

Плагины для дебага и профилирования в WordPress

В каталоге WP есть несколько хороших плагинов, которые расширяют возможности «дебага» и дают дополнительную информацию для выявления слабых мест кода. Популярные из них:

  • Query Monitor — выводит в подвале кучу полезной информации о текущем запросе. Сколько времени затрачено, сколько SQL запросов, какие запросы, сколько времени занял каждый запрос, сколько памяти затрачено, какие хуки использовались и т.д.

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

  • Log Deprecated Notices — записывает в лог все заметки о наличии устаревших функций WordPress или их параметров и т.д. Не зависит от WP_DEBUG — работает с отключенным WP_DEBUG.

  • WordPress mu-plugin for debugging — альтернативный дебаггер на базе библиотеки Kint.

  • Clockwork для WordPress — выводит любую отладочную информацию в консоль браузера Google Chrome или Firefox, работает на основе браузерного расширения Clockwork, чтобы иметь возможность передавать данные с сервера на клиент. Есть возможность отладки AJAX-запросов.

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

Подробнее

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

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

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

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

Подробнее

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

Например, вы разрабатываете тему или плагин, допустили ошибку в коде. Естественно сайт «упал». А из-за чего не понятно — WordPress показывает стандартное сообщение о технических неполадках.

Вот тут то нам и пригодится показ ошибок PHP.

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

Файл wp-config содержит основные параметры и настройки вашего сайта на WordPress. Он хранит такие важные данные как: настройки подключения к Базе Данных, префикс для таблиц БД и адрес для входа в админку, если WordPress установлен в подкаталог.

Добавьте следующий код в файл wp-config:

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

Возможно, эта строка уже присутствует в файле со значением FALSE. В таком случае не нужно дублировать ее, просто измените FALSE на TRUE.

С помощью этого кода вы переведете WordPress в режим отладки (debug mode). Нужно быть готовым к тому, что при включении режима отладки WordPress начнет отображать все предупреждения и ошибки на сайте в самом верху страницы как в админке, так и на самом сайте.

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

define( 'WP_DEBUG', false );

В разработке нужно иметь возможность смотреть где ошибка, когда что-то вдруг сломалось. В WordPress для этого есть специальный режим «дебаг» (режим отладки). В этой заметке разберем его на части и посмотрим что это за константа такая WP_DEBUG.

Зачем нужен «дебаг режим»?

Допустим, вы изменили код файла functions.php темы и сайт перестал работать. Вместо него белый экран — ничего не понятно. «дебаг» поможет разобраться, он покажет ошибку и скажет в какой она строке какого файла.

«Дебаг» выводит не только ошибки, из-за которых сайт перестает работать, но и заметки. Заметки могут создаваться самим PHP (например, когда неправильно используется переменная) или кодом PHP скрипта (например, WP создает такие заметки, если сайт использует устаревшую функцию WordPress, или устаревший параметр функции).

Читайте также

  • пример исправления скорости загрузки сайта через профилирование слабых мест с помощью xDebug + phpStorm.

  • Profiling WordPress Sites (видео)

Есть два варианта режима «дебаг»:

  1. WP_DEBUG_DISPLAY — Константа показа ошибок на экран.
  2. WP_DEBUG_LOG — Константа запись ошибок в лог файл.

Сам «дебаг» режим включается константой WP_DEBUG.

Все три константы могут принимать значения true или false.

По умолчанию константы дебага имеют такие значения:

  • WP_DEBUG = false (true при 'development' === wp_get_environment_type())
  • WP_DEBUG_DISPLAY = true
  • WP_DEBUG_LOG = false

Константы обычно определяются в файле wp-config.php.

wp_initial_constants() определяет дефолтные значения констнат, если они не установлены вручную. Функция срабатывает на раннем этапе загрузки WordPress.

wp_debug_mode() устанавливает настройки PHP на основе установленных констант.

WP_DEBUG_DISPLAY и WP_DEBUG_LOG активируются, только если включена константа WP_DEBUG.

Включение WP_DEBUG не изменяет значение других констант. Т.е. при WP_DEBUG=true WP_DEBUG_DISPLAY и WP_DEBUG_LOG сохранят свои дефолтные значения и на основе этих значений будут выставлены PHP настройки показа и логирования ошибок.

Отображение ошибок форсировано отключено для AJAX/REST/XMLRPC/JSONP запросов. См. код wp_debug_mode():

if (
	defined( 'XMLRPC_REQUEST' )
	|| defined( 'REST_REQUEST' )
	|| defined( 'MS_FILES_REQUEST' )
	|| ( defined( 'WP_INSTALLING' ) && WP_INSTALLING )
	|| wp_doing_ajax()
	|| wp_is_json_request()
) {
	ini_set( 'display_errors', 0 );
}

Как включить показ ошибок в AJAX запросе, сморите в статье про AJAX.

Важно отключать «дебаг» на рабочем сайте.

Базовое включение

Откройте файл wp-config.php в корне сайта и измените false на true в строке:

define( 'WP_DEBUG', true ); // false - отключить показ ошибок

При таком включении ошибки и заметки будут выводиться на экран, но ничего логироваться не будет.

Включение и настройка дебага

Код ниже, включит запись ошибок, предупреждений и заметок в файл wp-content/debug.log и выключит показ заметок и предупреждений на экране, чтобы они не мешались при просмотре сайта.

define( 'WP_DEBUG', true );     // включение дебаг режима
define( 'WP_DEBUG_LOG', true ); // true - логирование ошибок в файл /wp-content/debug.log
define( 'WP_DEBUG_DISPLAY', false ); // false - отключает показ ошибок на экране
define( 'SCRIPT_DEBUG', true ); // используем полные версии JS и CSS файлов движка

Вставлять этот код нужно в файл wp-config.php куда угодно, но до строки:

require_once( ABSPATH . 'wp-settings.php' );

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

error_log( $value );               // Скалярные величины
error_log( print_r( $value, 1) );  // Любые данные

Динамическое включение показа ошибок

Этот код помогает быстро включать константу WP_DEBUG, которая на рабочем сайте должна быть выключена. Также код позволяет включить запись ошибок в файл debug.log в папку /wp-content и отключить показ ошибок на экране.

Зачем это надо? Допустим, мы сделали сайт и на боевом сайте нам иногда нужно видеть ошибки (обычно конечно все это тестируется на локалке, но всякое бывает нужно). Чтобы видеть причину ошибки, нам нужно включить дебаг, но на боевом сайте где ходят пользователи делать этого не рекомендуется. С помощью кода ниже можно включить дебаг режим в WordPress через URL, зная определенный ключ.

Включение ошибок сохраняется в куку.

Установка

Замените строку define( WP_DEBUG, false ); в файле wp-config.php на такой код:

GitHub

<?php

/**
 * Dynamically enable/disable the display of PHP errors in WordPress.
 *
 * Installation:
 * replace line 'define( WP_DEBUG, false );' in 'wp-config.php' file with this code.
 *
 * Enabling debug mode:
 * NOTE: Strongly recommended to changing the 'debug' word to something more unique!
 * add the 'debug' query parameter to the URL. Examples:
 * https://site.com/?debug - default enabling of WP_DEBUG constant
 * https://site.com/?debug=1 - logging of errors into file 'DOCUMENT_ROOT/../php-errors-{HOST}.log'.
 * https://site.com/?debug=2 - linking uncompressed scripts and saving all SQL queries to $wpdb->queries
 * https://site.com/?debug=3 - saving all SQL queries in $wpdb->queries
 * https://site.com/?debug=4 - disable displaying errors (enabled by default)
 * https://site.com/?debug=14 - combining
 *
 * Disabling debug mode:
 * https://site.com/?debug=anything
 *
 * @author Kama (http://wp-kama.ru)
 * ver 2.5
 */
// IMPORTANT: change from `debug` to your unique key!
kama_define_wp_debug( 'debug' );

function kama_define_wp_debug( $key ){

	$val = isset( $_GET[ $key ] ) ? ( $_GET[ $key ] ?: 'yes' ) : false;

	// set/delete cookie
	if( $val !== false ){

		$cookie = preg_match( '/^(yes|[1234])$/', $val ) ? $val : null;

		$host = str_replace( 'www.', '', $_SERVER['HTTP_HOST'] );

		// cirilic domains: .сайт, .онлайн, .дети, .ком, .орг, .рус, .укр, .москва, .испытание, .бг
		false !== strpos( $host, 'xn--' )
			? preg_match( '~xn--[^.]+.xn--[^.]+$~', $host, $mm )
			: preg_match( '~[a-z0-9][a-z0-9-]{1,63}.[a-z.]{2,6}$~', $host, $mm );

		$host = $mm[0];

		$_COOKIE[ $key ] = $cookie;
		setcookie( $key, $cookie, time() + ( $cookie ? 3600 * 24 * 365 : -3600 ), '/', ".$host" );
	}

	// enable the debug based on the cookie
	if( ! empty( $_COOKIE[ $key ] ) ){

		define( 'WP_DEBUG', true );

		$set = array_flip(
			preg_split( '/(d)/', $_COOKIE[ $key ], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY )
		);

		isset( $set[1] ) && define( 'WP_DEBUG_LOG', dirname( $_SERVER['DOCUMENT_ROOT'] ) . "/php-errors-{$_SERVER['HTTP_HOST']}.log" );
		isset( $set[2] ) && define( 'SCRIPT_DEBUG', true );
		isset( $set[3] ) && define( 'SAVEQUERIES', true );
		isset( $set[4] ) && define( 'WP_DEBUG_DISPLAY', false );
	}
	else {
		define( 'WP_DEBUG', false );
	}
}

Теперь, чтобы включить режим WP_DEBUG, нужно добавить в любой URL сайта параметр запроса debug: http://example.com/?debug или http://example.com/?debug=1 (принудительный вывод на экран, если такой вывод отключен) или http://example.com/?debug=2 (логирование в файл).

Для защиты, ключ debug нужно изменить на свой, который будете знать только вы, потому что по нему вы будете включить/отключать дебаг режим.

При включении логирования, не забывайте удалять лог файл, а то его может посмотреть кто угодно. Или путь до файла лога можно изменить см. описание WP_DEBUG_LOG.

WP_DEBUG

WP_DEBUG — это PHP константа (глобальная постоянная — определяется всего один раз). Значение этой постоянной включает или отключает показ ошибок в PHP, а также она используется в разных местах кода WordPress для показа или подавления ошибок, где это необходимо.

WP_DEBUG нужно определять (устанавливать) в файле wp-config.php из корня сайта.

define( 'WP_DEBUG', false ); // дебаг отключен. По умолчанию.
// или
define( 'WP_DEBUG', true ); // дебаг включен

Для удобности, можно писать числа 1 или 0:

define( 'WP_DEBUG', 0 ); // дебаг отключен. По умолчанию.
// или
define( 'WP_DEBUG', 1 ); // дебаг включен

Заметка: нельзя указывать false в кавычках — ‘false’. В этом случае дебаг будет включен, потому что значение равно строке false, а не логическому — нет.

PHP ошибки, предупреждения и заметки (errors, warnings и notices)

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

  1. errors — серьезная ошибка, которая приводит к остановке скрипта. PHP прерывает работу.
  2. warnings — не ошибка, а предупреждение о чем-либо. PHP не прерывает работу.
  3. notices — не ошибка, а заметка о чем-либо. PHP не прерывает работу. Заметки могут показать возможные баги в коде. Их исправление, как правило, делает код более стабильным.

«Режим дебаг» включает все уровни ошибок. Это не похоже на обычное поведение PHP, там обычно включены только ошибки уровня errors, а warnings и notices не отображаются. Подробнее читайте в описании error_reporting().

Устаревшие функции, хуки и устаревшие параметры функций

WP_DEBUG также включает внутренние заметки самого WordPress. В WordPress есть специальные функции вроде _deprecated_function(), которые показывают ошибку уровня notices, когда используется устаревшая функция или хук или параметр хука, функции и т.д. Эти заметки предупреждают, что функция WP считается устаревшей и её нужно заменить, потому что она в любой момент может быть удалена. В таких заметках чаще всего предлагается альтернативная функция для замены.

WP_DEBUG_DISPLAY

По умолчанию: true.

Еще один компонент WP_DEBUG, который контролирует вывод (показ) ошибок на экран.

Зависит от WP_DEBUG! Работает только, если дебаг включен WP_DEBUG = true . В противном случае просто используется глобальное значение PHP опции display_errors.

Если указать в wp-config.php:

  • define( 'WP_DEBUG_DISPLAY', true ) — (по умолчанию) WP будет выводить (показывать) ошибки на экран.
  • define( 'WP_DEBUG_DISPLAY', false ) — ошибки не будут выводиться на экран. Это нужно, когда ошибки записываются в файл (см. WP_DEBUG_LOG) и их можно смотреть позднее.
  • define( 'WP_DEBUG_DISPLAY', null ) — WP вообще не будет указывать значение для PHP опции display_errors, т.е. будет использована глобальная настройка PHP (сервера).

Показ ошибок всегда отключается для REST, AJAX или XML-RPC запросов. Для них срабатывает такой код ini_set( ‘display_errors’, 0 ), но при этом значение константы WP_DEBUG_DISPLAY не изменяется!

WP_DEBUG_LOG

По умолчанию: false

Еще один компонент дебага. Включает запись ошибок в файл /wp-content/debug.log. Зависит от WP_DEBUG — работает только если WP_DEBUG равен true.

Запись ошибок в файл может пригодится, когда нужно проверить наличие ошибок в коде, который ничего не выводит на экран. Например, при AJAX запросе или при тестировании CRON или REST.

define( 'WP_DEBUG_LOG', true ); // true - запись ошибок в файл /wp-content/debug.log

Изменение адреса файла лога ошибок

Через WP

C WordPress 5.1, в WP_DEBUG_LOG можно указать путь к файлу лога:

define( 'WP_DEBUG_LOG', '/srv/path/to/custom/log/location/errors.log' );
Через PHP

Чтобы изменить название файла, добавьте следующую строку как можно раньше, например в MU плагины:

ini_set( 'error_log', WP_CONTENT_DIR . '/hidden-debug.log' );

Но эту строку нельзя добавлять в wp-config.php — это слишком рано…

Имейте ввиду:

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

SAVEQUERIES

По умолчанию: не определена.

Связанная с дебагом константана. При включении, все SQL запросы будут сохраняться в переменную $wpdb->queries в виде массива. В этом массиве можно будет посмотреть все SQL запросы и при необходимости найти нужный и убедиться что он правильный и т.п.

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

define( 'SAVEQUERIES', true ); // true - сохраняет SQL запросы и данные о них в  `$wpdb->queries`

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

SCRIPT_DEBUG

По умолчанию: false.

Связанная с дебагом константа. Контролирует какие JS и CSS файлы использовать: сжатые или полные. При включении WordPress будет использовать не сжатые версии (dev версии) JS и CSS файлов. По умолчанию используются min версии файлов. Это нужно для тестирования при изменении встроенных js или css файлов.

define( 'SCRIPT_DEBUG', true ); // true - использование полных версий `.css` и `.js` файлов

Как работает WP_DEBUG?

После установки констант дебага в wp-config.php мы заходим на сайт. И при генерации страницы, в самом начале загрузки WordPress (см. wp-settings.php) срабатывает функция wp_debug_mode(). Она, используя функции PHP, устанавливает как и какие уровни ошибок показывать, нужно ли создавать лог файл и т.д.

Не работает WP_DEBUG?

Иногда может возникнуть такая ситуация, когда вы включаете WP_DEBUG в конфиге, а ошибки все равно не видно. Такое поведение может возникнуть, когда где-то после установок параметров показа ошибок самим WordPress эти установки меняются. Например в MU плагине, обычном плагине или в теме, ошибки выключаются переустановкой ini директив PHP, примерно таким кодом:

error_reporting(0); // отключает сообщения об ошибках
ini_set('display_errors', 0); // отключает показ ошибок на экран

В этом случает установки дебага WP перебиваются и он перестает работать…

Для решения, лучше всего найти где изменяются настройки и удалить такие строки, чтобы дальше работать только с константой WP_DEBUG.

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

error_reporting(E_ALL); // включаем сообщения об ошибках
ini_set('display_errors', 1); // включаем показ ошибок на экран

Функции WP для дебага

  • wp_debug_backtrace_summary() — Получает трассировку с названиями функций — список названий всех функций/методов, которые были вызваны для того, чтобы добраться до текущего места в коде (откуда была вызвана эта функция).
  • wp_get_environment_type() — Получает текущий тип окружения: local, development, staging, production (по умолчанию).

Данные системы

Для дебага в WP есть класс WP_Debug_Data. Например, используя следующий метод мы можем получить кучу данных о системе:

require_once ABSPATH . '/wp-admin/includes/class-wp-debug-data.php';
require_once ABSPATH . '/wp-admin/includes/update.php';
require_once ABSPATH . '/wp-admin/includes/misc.php';

$data = WP_Debug_Data::debug_data();

print_r( $data );

Получим большой массив данных:

Array
(
	[wp-core] => Array
		(
			[label] => WordPress
			[fields] => Array
				(
					[version] => array( data )

					[site_language] => array( data )

					[user_language] => array( data )

					[timezone] => array( data )

					[home_url] => array( data )

					[site_url] => array( data )

					[permalink] => array( data )

					[https_status] => array( data )

					[multisite] => array( data )

					[user_registration] => array( data )

					[blog_public] => array( data )

					[default_comment_status] => array( data )

					[environment_type] => array( data )

					[user_count] => array( data )

					[dotorg_communication] => array( data )

				)

		)

	[wp-paths-sizes] => Array
		(
			[label] => Directories and Sizes
			[fields] => Array
				(
					[wordpress_path] => array( data )

					[wordpress_size] => array( data )

					[uploads_path] => array( data )

					[uploads_size] => array( data )

					[themes_path] => array( data )

					[themes_size] => array( data )

					[plugins_path] => array( data )

					[plugins_size] => array( data )

					[database_size] => array( data )

					[total_size] => array( data )

				)

		)

	[wp-dropins] => Array
		(
			[label] => Drop-ins
			[show_count] => 1
			[description] => Drop-ins are single files, found in the /public_html/assets directory, that replace or enhance WordPress features in ways that are not possible for traditional plugins.
			[fields] => Array
				(
					[maintenance.php] => array( data )

					[object-cache.php] => array( data )

				)

		)

	[wp-active-theme] => Array
		(
			[label] => Active Theme
			[fields] => Array
				(
					[name] => array( data )

					[version] => array( data )

					[author] => array( data )

					[author_website] => array( data )

					[parent_theme] => array( data )

					[theme_features] => array( data )

					[theme_path] => array( data )

					[auto_update] => array( data )

				)

		)

	[wp-parent-theme] => Array
		(
			[label] => Parent Theme
			[fields] => Array( data )
		)

	[wp-themes-inactive] => Array
		(
			[label] => Inactive Themes
			[show_count] => 1
			[fields] => Array
				(
					[Dummy] => array( data )

				)

		)

	[wp-mu-plugins] => Array
		(
			[label] => Must Use Plugins
			[show_count] => 1
			[fields] => Array
				(
					[disable-plugins-in-front.php] => array( data )

					[main.php] => array( data )

					[not_support_browsers_redirect.php] => array( data )

					[POMOdoro Translation Cache] => array( data )

					[protect-malicious-queries.php] => array( data )

					[Rus to Lat] => array( data )

				)

		)

	[wp-plugins-active] => Array
		(
			[label] => Active Plugins
			[show_count] => 1
			[fields] => Array
				(
					[AJAX Simply] => array( data )

					[Democracy Poll] => array( data )

					[Disable Emojis (GDPR friendly)] => array( data )

					[Display Active Plugins First] => array( data )

					[Kama Breadcrumbs] => array( data )

					[Kama Postviews] => array( data )

					[Kama SpamBlock] => array( data )

					[Kama Thumbnail Pro] => array( data )

					[Redis Object Cache] => array( data )

				)

		)

	[wp-plugins-inactive] => Array
		(
			[label] => Inactive Plugins
			[show_count] => 1
			[fields] => Array
				(
					[404 Error Monitor] => array( data )

					[Category Order and Taxonomy Terms Order] => array( data )

					[Contact Form 7] => array( data )

					[Kama Thumbnail] => array( data )

					[Query Monitor] => array( data )

					[Query Monitor Extend] => array( data )

					[Right Now Reloaded] => array( data )

					[Three Column Screen Layout] => array( data )

					[TinyPNG - JPEG, PNG & WebP image compression] => array( data )

					[User Role Editor] => array( data )

					[Widget Logic] => array( data )

					[WooCommerce] => array( data )

					[WordPress Sphinx Search Plugin] => array( data )

					[WP Crontrol] => array( data )

					[WP Super Cache] => array( data )

					[Yoast SEO] => array( data )

				)

		)

	[wp-media] => Array
		(
			[label] => Media Handling
			[fields] => Array
				(
					[image_editor] => array( data )

					[imagick_module_version] => array( data )

					[imagemagick_version] => array( data )

					[imagick_version] => array( data )

					[file_uploads] => array( data )

					[post_max_size] => array( data )

					[upload_max_filesize] => array( data )

					[max_effective_size] => array( data )

					[max_file_uploads] => array( data )

					[imagick_limits] => Array ( data )

					[imagemagick_file_formats] => Array( JPEG, JPG, MOV, MP4, MPEG, MPG, PNG, PNG24, WBMP, WEBP, WMV ... )

					[gd_version] => array( data )

					[gd_formats] => array( data )

					[ghostscript_version] => array( data )

				)

		)

	[wp-server] => Array
		(
			[label] => Server
			[description] => The options shown below relate to your server setup. If changes are required, you may need your web host’s assistance.
			[fields] => Array
				(
					[server_architecture] => array( data )

					[httpd_software] => array( data )

					[php_version] => array( data )

					[php_sapi] => array( data )

					[max_input_variables] => array( data )

					[time_limit] => array( data )

					[memory_limit] => array( data )

					[max_input_time] => array( data )

					[upload_max_filesize] => array( data )

					[php_post_max_size] => array( data )

					[curl_version] => array( data )

					[suhosin] => array( data )

					[imagick_availability] => array( data )

					[pretty_permalinks] => array( data )

				)

		)

	[wp-database] => Array
		(
			[label] => Database
			[fields] => Array
				(
					[extension] => array( data )

					[server_version] => array( data )

					[client_version] => array( data )

					[database_user] => array( data )

					[database_host] => array( data )

					[database_name] => array( data )

					[database_prefix] => array( data )

					[database_charset] => array( data )

					[database_collate] => array( data )

				)

		)

	[wp-constants] => Array
		(
			[label] => WordPress Constants
			[description] => These settings alter where and how parts of WordPress are loaded.
			[fields] => Array
				(
					[ABSPATH] => array( data )

					[WP_HOME] => array( data )

					[WP_SITEURL] => array( data )

					[WP_CONTENT_DIR] => array( data )

					[WP_PLUGIN_DIR] => array( data )

					[WP_MEMORY_LIMIT] => array( data )

					[WP_MAX_MEMORY_LIMIT] => array( data )

					[WP_DEBUG] => array( data )

					[WP_DEBUG_DISPLAY] => array( data )

					[WP_DEBUG_LOG] => array( data )

					[SCRIPT_DEBUG] => array( data )

					[WP_CACHE] => array( data )

					[CONCATENATE_SCRIPTS] => array( data )

					[COMPRESS_SCRIPTS] => array( data )

					[COMPRESS_CSS] => array( data )

					[WP_LOCAL_DEV] => array( data )

					[DB_CHARSET] => array( data )

					[DB_COLLATE] => Array
						(
						)

				)

		)

	[wp-filesystem] => Array
		(
			[label] => Filesystem Permissions
			[description] => Shows whether WordPress is able to write to the directories it needs access to.
			[fields] => Array
				(
					[wordpress] => array( data )

					[wp-content] => array( data )

					[uploads] => array( data )

					[plugins] => array( data )

					[themes] => array( data )

					[mu-plugins] => array( data )

				)

		)

)

Плагины для дебага и профилирования в WordPress

В каталоге WP есть несколько хороших плагинов, которые расширяют возможности «дебага» и дают дополнительную информацию для выявления слабых мест кода. Популярные из них:

  • Query Monitor — выводит в подвале кучу полезной информации о текущем запросе. Сколько времени затрачено, сколько SQL запросов, какие запросы, сколько времени занял каждый запрос, сколько памяти затрачено, какие хуки использовались и т.д.

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

  • Log Deprecated Notices — записывает в лог все заметки о наличии устаревших функций WordPress или их параметров и т.д. Не зависит от WP_DEBUG — работает с отключенным WP_DEBUG.

  • WordPress mu-plugin for debugging — альтернативный дебаггер на базе библиотеки Kint.

  • Clockwork для WordPress — выводит любую отладочную информацию в консоль браузера Google Chrome или Firefox, работает на основе браузерного расширения Clockwork, чтобы иметь возможность передавать данные с сервера на клиент. Есть возможность отладки AJAX-запросов.

In development, you need to be able to see where the error is when something suddenly breaks. WordPress has a special debug mode for this. In this post, let’s take it apart and see what this WP_DEBUG constant is.

Why do we need «debug mode»?

Let’s say you changed the functions.php file of the theme and the site stopped working. In its place is a white screen — nothing is clear. «Debug» will help to understand, it will show you the error and tell you in which line of what file it is.

«Debug» displays not only the errors that cause the site to stop working, but also the notes and warnings. Notes can be created by PHP itself (for example, when a variable is used incorrectly) or by PHP script code (for example, WP creates such notes if the site uses a deprecated WordPress function, or an deprecated function parameter).

There are two options for debug mode:

  1. WP_DEBUG_DISPLAY — Display errors on the screeen.
  2. WP_DEBUG_LOG — Write errors to log file.

The debug mode itself is controlled by WP_DEBUG constant.

All three constants can take true or false values.

By default, the debug constants have these values:

  • WP_DEBUG = false (true when 'development' === wp_get_environment_type())
  • WP_DEBUG_DISPLAY = true
  • WP_DEBUG_LOG = false

All constants can be defined in the wp-config.php file or defined by wp_initial_constants(), which is triggered early on WordPress loading.

WP_DEBUG_DISPLAY and WP_DEBUG_LOG are activated only if the WP_DEBUG constant is enabled.

Enabling WP_DEBUG does not change the value of the other constants. That is, with WP_DEBUG=true WP_DEBUG_DISPLAY and WP_DEBUG_LOG will retain their default values and PHP display and error logging settings will be based on those values.

The wp_debug_mode() function sets the PHP settings based on the values of those constants.

Error display is always disabled for AJAX requests, you can only see errors there through the log file. This is set in wp_debug_mode():

if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {
	@ini_set( 'display_errors', 0 );
}

How to enable error display in an AJAX request, see article about AJAX.

It is important to disable «debugging» on the working (production) site.

How to enable «debug» (display errors in WordPress)

Basic enabling

Open the wp-config.php file at the root of your site and change false to true on the line:

define( `WP_DEBUG`, true ); // false - turn off error display

With this option errors and noties will be displayed, but nothing will be logged in log file.

Enable and configure debugging

The code below, will enable the recording of errors, warnings and noties in the wp-content/debug.log file and disable the display of notes and warnings on the screen, so they do not get in the way when browsing the site.

define( 'WP_DEBUG', true );          // enable debug mode
define( 'WP_DEBUG_LOG', true );      // true - logging errors into /wp-content/debug.log file
define( 'WP_DEBUG_DISPLAY', false ); // false - turns off displaying errors on the screen
define( 'SCRIPT_DEBUG', true );      // use full versions of JS and CSS engine files

Insert this code anywhere in the wp-config.php file, but before the line:

require_once( ABSPATH . 'wp-settings.php' );

Thanks to the code above, error logging to a file has been enabled. This can be used to write the contents of the variables to log file:

error_log( $value );               // Scalar values
error_log( print_r( $value, 1) );  // Any data

Dynamically turn on/off errors display

This code helps to quickly enable the WP_DEBUG constant, which on a working site should be turned off. The code also allows you to enable error logging in the /wp-content/debug.log file, and disable error display on the screen.

Why this code is handy? Let’s say we made the site and it works, but we periodically fix it’s code. While editing of course appear different errors, including fatal ones. To see what the cause, we need to enable debug, to do this, open wp-config.php and change the constant, after completion it is necessary to return everything back. This is inconvenient, it’s more convenient to enable debug via URL and see errors when needed.

Enabling errors is saved in the cookie of your site so it will works only for you.

To get things working, replace line define( WP_DEBUG, false ); in file wp-config.php with this code:

GitHub

<?php

/**
 * Dynamically enable/disable the display of PHP errors in WordPress.
 *
 * Installation:
 * replace line 'define( WP_DEBUG, false );' in 'wp-config.php' file with this code.
 *
 * Enabling debug mode:
 * NOTE: Strongly recommended to changing the 'debug' word to something more unique!
 * add the 'debug' query parameter to the URL. Examples:
 * https://site.com/?debug - default enabling of WP_DEBUG constant
 * https://site.com/?debug=1 - logging of errors into file 'DOCUMENT_ROOT/../php-errors-{HOST}.log'.
 * https://site.com/?debug=2 - linking uncompressed scripts and saving all SQL queries to $wpdb->queries
 * https://site.com/?debug=3 - saving all SQL queries in $wpdb->queries
 * https://site.com/?debug=4 - disable displaying errors (enabled by default)
 * https://site.com/?debug=14 - combining
 *
 * Disabling debug mode:
 * https://site.com/?debug=anything
 *
 * @author Kama (http://wp-kama.ru)
 * ver 2.5
 */
// IMPORTANT: change from `debug` to your unique key!
kama_define_wp_debug( 'debug' );

function kama_define_wp_debug( $key ){

	$val = isset( $_GET[ $key ] ) ? ( $_GET[ $key ] ?: 'yes' ) : false;

	// set/delete cookie
	if( $val !== false ){

		$cookie = preg_match( '/^(yes|[1234])$/', $val ) ? $val : null;

		$host = str_replace( 'www.', '', $_SERVER['HTTP_HOST'] );

		// cirilic domains: .сайт, .онлайн, .дети, .ком, .орг, .рус, .укр, .москва, .испытание, .бг
		false !== strpos( $host, 'xn--' )
			? preg_match( '~xn--[^.]+.xn--[^.]+$~', $host, $mm )
			: preg_match( '~[a-z0-9][a-z0-9-]{1,63}.[a-z.]{2,6}$~', $host, $mm );

		$host = $mm[0];

		$_COOKIE[ $key ] = $cookie;
		setcookie( $key, $cookie, time() + ( $cookie ? 3600 * 24 * 365 : -3600 ), '/', ".$host" );
	}

	// enable the debug based on the cookie
	if( ! empty( $_COOKIE[ $key ] ) ){

		define( 'WP_DEBUG', true );

		$set = array_flip(
			preg_split( '/(d)/', $_COOKIE[ $key ], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY )
		);

		isset( $set[1] ) && define( 'WP_DEBUG_LOG', dirname( $_SERVER['DOCUMENT_ROOT'] ) . "/php-errors-{$_SERVER['HTTP_HOST']}.log" );
		isset( $set[2] ) && define( 'SCRIPT_DEBUG', true );
		isset( $set[3] ) && define( 'SAVEQUERIES', true );
		isset( $set[4] ) && define( 'WP_DEBUG_DISPLAY', false );
	}
	else {
		define( 'WP_DEBUG', false );
	}
}

Now, to enable WP_DEBUG mode, you need to add ?debugquery parameter to any URL, for example:

  • http://example.com/?debug — enables debug.
  • http://example.com/?debug=1 — forced output to screen if such output is disabled.
  • http://example.com/?debug=2 — logging to file.

For security reason, strongly recommended change the ?debug parameter, specify something rare and known only to you.

When enabling error logging (?debug=2) the site parent folder (DOCUMENT_ROOT/..) must be writable, otherwise PHP will not be able to create the log file. Or you can manually create a log file DOCUMENT_ROOT/../php-errors-example.com.log. It must have write permissions (CHMOD 660 or higher).

WP_DEBUG

WP_DEBUG — is a PHP constant (a global constant — only defined once). The value of this constant enables or disables error display in PHP. It is also used in various places in WordPress code to show or suppress errors where necessary.

WP_DEBUG should be defined in the wp-config.php file.

// disable debug (default)
define( 'WP_DEBUG', false );
// or
define( 'WP_DEBUG', 0 );

// enable debug
define( 'WP_DEBUG', true );
// or
define( 'WP_DEBUG', 1 );

Note: do not set false in quotes — 'false'. In this case the debug will be enabled because the value of string ‘false’ is logical true.

PHP errors, warnings and notices

There are different levels of errors in PHP. Without going into details, the significance levels are:

  1. errors — a serious error which leads to a halt of the script. Aborts PHP.
  2. warnings — not an error, but a warning about something. PHP does not interrupt.
  3. notices — not an error, but a note about something. PHP does not interrupt. Notes may indicate possible bugs in the code. Fixing them will usually make the code more stable.

«Debug mode» includes all levels of errors. This is not like PHP’s usual behavior: usually only errors at the ‘errors’ level are included, and warnings and notices are not shown. See error_reporting() for more details.

Deprecated functions, hooks and deprecated function parameters

WP_DEBUG also includes internal WordPress noties. WordPress has special functions like _deprecated_function(), which show a notices level error when an deprecated function or hook or parameter of a hook, function, etc. is used. These notices warn that the WP function is considered deprecated and should be replaced because it can be removed at any time. Such notes most often suggest an alternative function to replace it.

WP_DEBUG_DISPLAY

Default: true.

Another WP_DEBUG component, which controls the display of errors.

IMPORTANT: it depends on WP_DEBUG — the logic of this parameter works only if WP_DEBUG = true. Otherwise, the global PHP option display_errors is used as the value of WP_DEBUG_DISPLAY.

If you specify in wp-config.php:

  • define( 'WP_DEBUG_DISPLAY', true ) — (by default) WP will display errors.

  • define( 'WP_DEBUG_DISPLAY', false ) — The errors will not be displayed. This is needed when errors are written to a log file (see WP_DEBUG_LOG) and you can see them later.

  • define( 'WP_DEBUG_DISPLAY', null ) — WP will not specify a value for PHP option display_errors at all, i.e. it will use the global PHP (server) setting.

Error display is always turned off for REST, AJAX or XML-RPC requests. Such code ini_set(‘display_errors’, 0 ) works for those requests forcibly. The value of WP_DEBUG_DISPLAY constant does not change!

WP_DEBUG_LOG

Default: false.

Another debug component. Enables error logging to file /wp-content/debug.log. Depends on WP_DEBUG — works only if WP_DEBUG = true.

Writing errors in the log file can be useful when you want catch errors, which does not display anything on the screen. For example, when AJAX request or when testing CRON or REST.

«php
define( ‘WP_DEBUG_LOG’, true ); // true — log errors to /wp-content/debug.log

#### Changing the address of the error log file

##### Via WP

Since WordPress 5.1, in ``WP_DEBUG_LOG`` you can specify the log file path:

```php
define( 'WP_DEBUG_LOG', '/srv/path/to/custom/log/location/errors.log' );
Via PHP

To change the file name, add the following line as early as possible, such as in MU plugins:

ini_set( 'error_log', WP_CONTENT_DIR . '/hidden-debug.log' );

This line cannot be added to wp-config.php — it’s too early!

  • The end folder in the specified path must exist and be writable.
  • The file inside may not exist, it will be created as soon as the first error occurs.

SAVEQUERIES

Default: undefined.

Related to debug constant. When enabled, all SQL queries will be saved in the $wpdb->queries property as an array. In this array you can see all SQL queries and if necessary find the right one and make sure it is correct, etc.

In addition to the query itself, also recorded data about how much time the query took and what function it was called.

// save SQL queries and their data in `$wpdb->queries`
define( 'SAVEQUERIES', true );

Important! this option requires additional memory and PHP operations. Therefore, for performance reasons, this constant should be used only while site development.

SCRIPT_DEBUG

Default: false.

A debug-related constant. Controls which JS and CSS files to use: compressed or full. When enabled, WordPress will use uncompressed versions (dev versions) of JS and CSS files. The default is to use min versions of the files. This is necessary for testing when modifying embedded js or css files.

// use full versions of WP `.css` and `.js` files
define( 'SCRIPT_DEBUG', true );

How does WP_DEBUG work?

After setting the debug constants in wp-config.php we go to the site. And when generating the page, at the very beginning of WordPress loading — see wp-settings.php — wp_debug_mode() function is triggered. It uses PHP functions to set how and what error levels to show, whether or not to create a log file, etc.

WP_DEBUG does not work?

Sometimes you may have a situation when you enable WP_DEBUG in wp-config, but the error is still not visible. This behavior can occur when somewhere after the error display settings by WordPress itself, these settings are changed. For example in MU plugin, a regular plugin or in the theme, the errors are turned off by reinstalling the ini directives PHP, something like this code:

error_reporting( 0 ); // turn off error messages
ini_set( 'display_errors', 0 ); // disables displaying errors

In this case WP’s debug settings get interrupted and it stops working.

To solve this, it is best to find where the settings are changed and delete such lines, so that from now on you can work only with WP_DEBUG constant.

As another solution, you can try to re-build the error output settings by specifying them again:

error_reporting( E_ALL ); // enable error messages
ini_set( 'display_errors', 1 ); // show errors on the screen

WP functions for debugging

  • wp_debug_backtrace_summary() — Return a comma-separated string of functions that have been called to get to the current point in code.
  • wp_get_environment_type() — Retrieves the current environment type.

System data

For debugging, WP has a class WP_Debug_Data. For example, using the following method we can get a bunch of data about the system:

require_once ABSPATH . '/wp-admin/includes/class-wp-debug-data.php';
require_once ABSPATH . '/wp-admin/includes/update.php';
require_once ABSPATH . '/wp-admin/includes/misc.php';

$data = WP_Debug_Data::debug_data();

print_r( $data );

We get a big data set:

Array
(
	[wp-core] => Array
		(
			[label] => WordPress
			[fields] => Array
				(
					[version] => array( data )

					[site_language] => array( data )

					[user_language] => array( data )

					[timezone] => array( data )

					[home_url] => array( data )

					[site_url] => array( data )

					[permalink] => array( data )

					[https_status] => array( data )

					[multisite] => array( data )

					[user_registration] => array( data )

					[blog_public] => array( data )

					[default_comment_status] => array( data )

					[environment_type] => array( data )

					[user_count] => array( data )

					[dotorg_communication] => array( data )

				)

		)

	[wp-paths-sizes] => Array
		(
			[label] => Directories and Sizes
			[fields] => Array
				(
					[wordpress_path] => array( data )

					[wordpress_size] => array( data )

					[uploads_path] => array( data )

					[uploads_size] => array( data )

					[themes_path] => array( data )

					[themes_size] => array( data )

					[plugins_path] => array( data )

					[plugins_size] => array( data )

					[database_size] => array( data )

					[total_size] => array( data )

				)

		)

	[wp-dropins] => Array
		(
			[label] => Drop-ins
			[show_count] => 1
			[description] => Drop-ins are single files, found in the /public_html/assets directory, that replace or enhance WordPress features in ways that are not possible for traditional plugins.
			[fields] => Array
				(
					[maintenance.php] => array( data )

					[object-cache.php] => array( data )

				)

		)

	[wp-active-theme] => Array
		(
			[label] => Active Theme
			[fields] => Array
				(
					[name] => array( data )

					[version] => array( data )

					[author] => array( data )

					[author_website] => array( data )

					[parent_theme] => array( data )

					[theme_features] => array( data )

					[theme_path] => array( data )

					[auto_update] => array( data )

				)

		)

	[wp-parent-theme] => Array
		(
			[label] => Parent Theme
			[fields] => Array( data )
		)

	[wp-themes-inactive] => Array
		(
			[label] => Inactive Themes
			[show_count] => 1
			[fields] => Array
				(
					[Dummy] => array( data )

				)

		)

	[wp-mu-plugins] => Array
		(
			[label] => Must Use Plugins
			[show_count] => 1
			[fields] => Array
				(
					[disable-plugins-in-front.php] => array( data )

					[main.php] => array( data )

					[not_support_browsers_redirect.php] => array( data )

					[POMOdoro Translation Cache] => array( data )

					[protect-malicious-queries.php] => array( data )

					[Rus to Lat] => array( data )

				)

		)

	[wp-plugins-active] => Array
		(
			[label] => Active Plugins
			[show_count] => 1
			[fields] => Array
				(
					[AJAX Simply] => array( data )

					[Democracy Poll] => array( data )

					[Disable Emojis (GDPR friendly)] => array( data )

					[Display Active Plugins First] => array( data )

					[Kama Breadcrumbs] => array( data )

					[Kama Postviews] => array( data )

					[Kama SpamBlock] => array( data )

					[Kama Thumbnail Pro] => array( data )

					[Redis Object Cache] => array( data )

				)

		)

	[wp-plugins-inactive] => Array
		(
			[label] => Inactive Plugins
			[show_count] => 1
			[fields] => Array
				(
					[404 Error Monitor] => array( data )

					[Category Order and Taxonomy Terms Order] => array( data )

					[Contact Form 7] => array( data )

					[Kama Thumbnail] => array( data )

					[Query Monitor] => array( data )

					[Query Monitor Extend] => array( data )

					[Right Now Reloaded] => array( data )

					[Three Column Screen Layout] => array( data )

					[TinyPNG - JPEG, PNG & WebP image compression] => array( data )

					[User Role Editor] => array( data )

					[Widget Logic] => array( data )

					[WooCommerce] => array( data )

					[WordPress Sphinx Search Plugin] => array( data )

					[WP Crontrol] => array( data )

					[WP Super Cache] => array( data )

					[Yoast SEO] => array( data )

				)

		)

	[wp-media] => Array
		(
			[label] => Media Handling
			[fields] => Array
				(
					[image_editor] => array( data )

					[imagick_module_version] => array( data )

					[imagemagick_version] => array( data )

					[imagick_version] => array( data )

					[file_uploads] => array( data )

					[post_max_size] => array( data )

					[upload_max_filesize] => array( data )

					[max_effective_size] => array( data )

					[max_file_uploads] => array( data )

					[imagick_limits] => Array ( data )

					[imagemagick_file_formats] => Array( JPEG, JPG, MOV, MP4, MPEG, MPG, PNG, PNG24, WBMP, WEBP, WMV ... )

					[gd_version] => array( data )

					[gd_formats] => array( data )

					[ghostscript_version] => array( data )

				)

		)

	[wp-server] => Array
		(
			[label] => Server
			[description] => The options shown below relate to your server setup. If changes are required, you may need your web host’s assistance.
			[fields] => Array
				(
					[server_architecture] => array( data )

					[httpd_software] => array( data )

					[php_version] => array( data )

					[php_sapi] => array( data )

					[max_input_variables] => array( data )

					[time_limit] => array( data )

					[memory_limit] => array( data )

					[max_input_time] => array( data )

					[upload_max_filesize] => array( data )

					[php_post_max_size] => array( data )

					[curl_version] => array( data )

					[suhosin] => array( data )

					[imagick_availability] => array( data )

					[pretty_permalinks] => array( data )

				)

		)

	[wp-database] => Array
		(
			[label] => Database
			[fields] => Array
				(
					[extension] => array( data )

					[server_version] => array( data )

					[client_version] => array( data )

					[database_user] => array( data )

					[database_host] => array( data )

					[database_name] => array( data )

					[database_prefix] => array( data )

					[database_charset] => array( data )

					[database_collate] => array( data )

				)

		)

	[wp-constants] => Array
		(
			[label] => WordPress Constants
			[description] => These settings alter where and how parts of WordPress are loaded.
			[fields] => Array
				(
					[ABSPATH] => array( data )

					[WP_HOME] => array( data )

					[WP_SITEURL] => array( data )

					[WP_CONTENT_DIR] => array( data )

					[WP_PLUGIN_DIR] => array( data )

					[WP_MEMORY_LIMIT] => array( data )

					[WP_MAX_MEMORY_LIMIT] => array( data )

					[WP_DEBUG] => array( data )

					[WP_DEBUG_DISPLAY] => array( data )

					[WP_DEBUG_LOG] => array( data )

					[SCRIPT_DEBUG] => array( data )

					[WP_CACHE] => array( data )

					[CONCATENATE_SCRIPTS] => array( data )

					[COMPRESS_SCRIPTS] => array( data )

					[COMPRESS_CSS] => array( data )

					[WP_LOCAL_DEV] => array( data )

					[DB_CHARSET] => array( data )

					[DB_COLLATE] => Array
						(
						)

				)

		)

	[wp-filesystem] => Array
		(
			[label] => Filesystem Permissions
			[description] => Shows whether WordPress is able to write to the directories it needs access to.
			[fields] => Array
				(
					[wordpress] => array( data )

					[wp-content] => array( data )

					[uploads] => array( data )

					[plugins] => array( data )

					[themes] => array( data )

					[mu-plugins] => array( data )

				)

		)

)

Plugins for debugging and profiling in WordPress

There are several plugins in the WP catalog that extend the «debugging» capabilities and provide additional information to identify code weaknesses. Popular ones are:

  • Query Monitor — displays a bunch of useful information about the current page query. How much time was spent, how many SQL queries, what queries, how long each query took, how much memory was spent, what hooks were used, etc.

  • Query Monitor Addons

No one likes to see errors on their website. Not only do they look bad to visitors and potential customers, but they also indicate that something’s wrong. But they’re, unfortunately, an inevitable part of running a site. The good news is that following a few best practices and being proactive can dramatically reduce the number of errors you experience. 

One way to monitor potential site issues — or troubleshoot existing ones — is to keep and review an error log. Let’s dive into this a bit more.

What is error logging and why is it important?

Error logging is the process of tracking and monitoring issues that occur on a website. This is usually done with a record of simple text files that live on your web server and are updated whenever an error occurs. Error logs are used to identify the number of problems that occur, provide details about each one, and show when it took place.

How to enable error logging

To enable error logging on your WordPress site, you’ll need sFTP access, available with WordPress.com plugin-enabled plans. This allows you to edit your website files remotely. In this case, you’ll be working with the wp-config.php file, which holds the basic configuration settings for your website.

A word of warning: you should only use sFTP and edit your wp-config.php file if you feel comfortable doing so. Mistakes can cause catastrophic errors on your website. If you don’t have experience changing these types of files, you may want to hire a developer or reach out to WordPress.com support for help.

1. Connect to your website via sFTP

You’ll need to start by enabling sFTP on your site. Go to My Site(s) → Settings → Hosting Configuration and click the Enable SFTP button.

Then, you’ll see your sFTP login details: URL, Port Number, Username, and Password. You’ll need to input these into FTP software, like FileZilla, to access your site. Follow these detailed instructions to connect to your WordPress.com website.

2. Find and download your wp-config.php file

Navigate to your wp-config.php file. This sits in the root directory of your file structure, alongside folders such as wp-content. Download this file, so you have a backup copy on hand.

3. Edit the wp-config.php file

Edit your wp-config.php file using a text editor such as Notepad.

Look for define( ‘WP_DEBUG’, false ); and replace this text with the following:

define( ‘WP_DEBUG’, true );

if ( WP_DEBUG ) {

        @error_reporting( E_ALL );

        @ini_set( ‘log_errors’, true );

        @ini_set( ‘log_errors_max_len’, ‘0’ );

        define( ‘WP_DEBUG_LOG’, true );

        define( ‘WP_DEBUG_DISPLAY’, false );

        define( ‘CONCATENATE_SCRIPTS’, false );

        define( ‘SAVEQUERIES’, true );

}

You’ve now successfully enabled error logging. You should only have this feature turned on while troubleshooting. Otherwise, it can leave your site more vulnerable to hacking attempts. To disable logging, simply delete the code you just added and restore the following:

define( ‘WP_DEBUG’, false );

How to view the error log manually

Once the log is enabled, you’ll need to load your website to trigger any error codes. Those codes are stored in a file called debug.log, which you can access via sFTP by following the same steps as above. 

You can find the debug.log file inside of the wp-content folder. If there are errors, the file will appear. However, if there aren’t any errors, then you won’t see it at all — congratulations!

Once you find the file, download it to your computer to view the full log, using a text editing software like Notepad. It will look something like this:

This file will provide valuable information that will point you, or your developer, to the source of your problem. 

How to view the error log using a plugin 

Using a plugin to find your error log can be an easier and faster method, depending on your level of experience. In the WordPress dashboard, click on Plugins → Add New. Search for “Error Log Monitor” and click Install → Activate.

This plugin installs a widget on your WordPress dashboard that allows you to access your error log. If you haven’t enabled error logging correctly, the widget will display instructions on how to do so. However, you should ignore these instructions, as they’re incorrect for a WordPress.com installation. Instead, use the ones listed above.

If you can’t see the dashboard widget, click on the Screen options tab at the top of the WordPress dashboard and ensure that “PHP error log” is checked.

How to find the plugin or theme that’s causing an error

Error logs are not inherently easy to read, but they do give insightful information into the cause of an error.

Typically, each line in your error log will display a message, alongside the date and time it happened and the file in which the error occurred. It also lists the line number where the error is located. For example:

Apr 20, 15:08:59

Notice: Undefined index: fg2 in /wordpress/themes/pub/varia/functions.php on line 166

Let’s break this down. First of all, there’s the date and time of the error: April 20, 15:08:59. This helps you determine if this was a one-off glitch or a recurring issue.

Then, you can see the type of error that’s been logged. Here are a few common types of error you may see here:

  • Notice. These are more warnings than errors, as they don’t actually stop your website code from executing. While you should still address a notice, your site will most likely still function, although potentially not as designed.
  • Parse error. This is typically the result of a mistake in the syntax of the underlying PHP code of the website (often in a theme or plugin). Parse errors include things like missing semicolons, parentheses, and other similar mistakes. A parse error will stop executing code when it hits the problem, so your site may look visibly broken or not function as intended.
  • Fatal error. This is often caused by undefined functions or classes, like a typo or poor coding practice. You can avoid it by using high-quality code, along with functions such as class_exists or function_exists.

In this case, the error is a notice.

Next, we see the error itself. In the example above the error is “undefined index.” This is followed by the specific location of the problem. In the above example, the error is occurring with the functions.php file of the Varia theme.

How to fix errors

Now that you can see your errors, it’s time to troubleshoot. Here’s a few things you can try:

  • If you’re a developer and the error is in your custom code, go to the line number in the log entry and work to debug.
  • If the error is within a theme or plugin, start by checking for any available updates. Keeping your plugins and themes up to date is critical for avoiding bugs and maintaining website security. Once you’ve applied any updates, re-check the error log to see if there are any new entries. If the error still exists, reach out to the plugin author or consider switching to an alternative. 
  • The error may also be caused by a conflict between two plugins. Try using the WordPress troubleshooting mode to fix this problem.
  • If the problem occurred immediately after installing or updating a plugin, deactivate it to see if the error persists. If it doesn’t, the plugin is the likely cause and you may want to find an alternative. If the error occured after a core update, you may need to manually deactivate plugins to find the source.

Troubleshooting with the WordPress error log

WordPress, like any software, may occasionally run into problems. It may seem confusing to find and fix those problems, but the error log can be a huge help! It enables you to learn valuable information that can help you troubleshoot and solve site errors in a timely manner.

To avoid errors, always use well-maintained plugins and themes, and keep on top of updates. Need more help? If you have a WordPress plugin-enabled plan, you benefit from world-class Happiness Engineers that can provide guidance.

In a perfect world, you’d never have a single issue that required debugging. But in the real world, you’ll almost certainly run into issues on your WordPress site that require a look under the hood.

To help you do that, WordPress includes its own built-in debug mode and you can also find useful third-party tools to help you debug WordPress.

In this post, we’ll dig into the built-in WordPress debug mode and show you how to enable it. Then, we’ll also share some of the other ways in which you can debug your WordPress site.

Here’s everything that we’ll cover:

  • An introduction to WordPress debug mode and the debug log
  • How to enable WordPress debug mode (three methods)
  • Some other ways to debug WordPress

What Does WP Debug Do?

The core WordPress software is written in PHP, as are plugins and themes.

If you’re having issues with your site, WordPress debug mode can help you find out what’s going wrong by displaying all PHP errors, notices, and warnings.

Once you enable debug mode, you’ll see messages like this whenever there’s an issue (even if it’s not causing immediate problems):

WP_DEBUG example of error on WordPress site

WP_DEBUG example of error on WordPress site

You can then fix the problem or report it to your developer or the theme/plugin’s developer.

What Is the WordPress Debug Log?

When you enable WordPress debug mode by itself, you’ll see messages like the example above on your site in the moment – but those messages won’t be saved anywhere.

If you want to save them, you can also enable the WordPress debug log to save all of those messages and errors to a file on your server.

When enabled by setting the WP_DEBUG_LOG constant to true, WordPress will write all issues to the following file:

wp-content/debug.log

However, you can also specify a custom file path to write the log to a different location on your server.

If you want to save problems to the log but not publicly display them within the HTML of your pages (like the example screenshot above), you can also use the WP_DEBUG_DISPLAY constant to keep debug mode enabled but not display messages on your site.

Typically, you’ll want to combine WP_DEBUG_DISPLAY with WP_DEBUG_LOG.

Ready to debug your #WordPress site? This guide has you covered 🐛Click to Tweet

How to Enable WordPress Debug Mode

To enable WordPress debug mode, you have several options. We’ll cover three methods to enable it:

How to Enable WordPress Debug Mode in MyKinsta

If you host your WordPress site at Kinsta, we built an easy tool that lets you enable the WordPress debug mode without needing to edit your wp-config.php file.

This tool is convenient for being able to quickly enable debug mode and display messages on your site, but it doesn’t let you control the WordPress debug log or whether or not to display messages on live pages. If you want to use just the debug log, you might prefer the plugin method in the next section.

To get started:

  • Open your MyKinsta dashboard.
  • Select the site where you want to enable debugging from the Sites list.
  • Go to the Tools tab in that site’s dashboard.
  • Click Enable under WordPress debugging.

How to enable WordPress debug mode in MyKinsta

How to enable WordPress debug mode in MyKinsta

You can use the tool on both your live and staging environments. Whenever possible, though, we’d recommend using it with your staging environment because enabling WordPress debug mode might display details about your site’s PHP code to visitors (which is confusing for visitors and also a security risk).

When you’re finished, you can disable debug mode by clicking the Disable button in your Kinsta dashboard:

How to disable WordPress debug mode in MyKinsta

How to disable WordPress debug mode in MyKinsta

How to Use a WordPress Debug Plugin

If you’re not hosting at Kinsta, you can also find free WordPress debug plugins that make it easy to enable debug mode. There are several options at WordPress.org, but we recommend the free WP Debugging plugin from Andy Fragen.

WP Debugging WordPress plugin

WP Debugging WordPress plugin

Once you install and activate the plugin, it starts working right away. By default, it sets the following constants to true (that is, it enables the following features):

  • WP_DEBUG – enables debug mode.
  • WP_DEBUG_LOG – saves messages to a log file.
  • SCRIPT_DEBUG
  • SAVEQUERIES

We’ll cover what the last two constants do a little later on in this post.

To configure a few options, you can go to Tools → WP Debugging:

The settings are for the WP Debugging plugin

WP Debugging plugin’s settings

Once you’re finished, make sure to disable the plugin to disable debug mode.

How to Manually Enable WordPress Debug Mode

Finally, you can also enable WordPress debug mode by manually adding the constants to your wp-config.php file.

To get started, connect to your server via FTP and edit the wp-config.php file. By default, this file is in the root folder of your site (unless you moved it for security reasons).

To enable just the basic WordPress debug mode, add the following code snippet above the line that says /* That’s all, stop editing! Happy blogging. */:

// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

You can also use some of the following constants according to your preferences:

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

Once you’re finished, you can either set the constants to false or just remove the snippet to disable debug mode.

Make Sure to Disable Debug Mode in WordPress When You’re Finished

The debug mode is useful when you’re trying to troubleshoot problems with WordPress, but you shouldn’t leave it enabled 24/7 because it can reveal text from your PHP code to website visitors.

We mentioned this above – but this is just a reminder to always disable debug mode when you’re finished troubleshooting.

Other Ways to Debug WordPress

Beyond the built-in debug tool that we featured above, there are several other built-in and third-party tools to help you debug your WordPress site.

Script Debug

SCRIPT_DEBUG is another built-in constant that forces WordPress to use the dev versions of core CSS and JavaScript files instead of the minified versions that it usually loads.

This can be helpful if you’re testing changes to the built-in .js or .css files.

To enable SCRIPT_DEBUG, you can either:

  • Use the free WP Debugging plugin from above, which enables it by default.
  • Add the following constant to your wp-config.php file – define( 'SCRIPT_DEBUG', true );

Database Query Debugging

If you’re having issues with your site’s database, you can enable database query logging using the SAVEQUERIES constant to track:

  • Each database query.
  • The function that called the database query.
  • How long the query took.

To enable query logging, you can either:

  • Use the free WP Debugging plugin from above, which enables it by default.
  • Add the following constant to your wp-config.php file – define( 'SAVEQUERIES', true );

Note: this will impact your site’s performance so try to use it on a staging site whenever possible and disable it as soon as you’re finished.

Query Monitor Plugin

The Query Monitor plugin is a free plugin that’s helpful for debugging a number of different areas in WordPress including:

  • Database queries.
  • PHP errors.
  • Hooks and actions.
  • Block editor blocks.
  • Enqueued scripts and stylesheets.
  • HTTP API calls.
  • User capabilities.

Overall, it’s one of the best WordPress debug tools that you’ll find, which is why it has almost a perfect 5-star rating on over 320 reviews.

Once you install and activate the plugin, you’ll get some new options on the WordPress toolbar that display debug information. When clicked, those options will open a new Query Monitor box that gives you more information:

The Query Monitor plugin

The Query Monitor plugin

For a more detailed look, we have an entire post on how to use the Query Monitor plugin.

New Relic

New Relic is a premium tool for analyzing and debugging your site’s performance. It can help you discover bottlenecks and issues that are affecting your site’s performance.

Kinsta already includes the built-in APM tool. However, you can still use New Relic in the MyKinsta dashboard, provided you have your own license.

Server Logs

Finally, your server logs can also be a useful tool in debugging WordPress.

If you host at Kinsta, you can view all of your server logs from the Logs tab in a site’s dashboard:

Viewing server logs in MyKinsta dashboard

Viewing server logs in MyKinsta dashboard

If you host elsewhere, you’ll need to consult your host’s documentation to learn where you can access your server logs.

It’s time to take a look under the hood and debug your #WordPress site 🐛 This guide has everything you need to get started 💪Click to Tweet

Summary

If you need to debug WordPress, the built-in WordPress debug mode provides a useful way to view PHP errors and notices.

If you host at Kinsta, you can enable it right from your dashboard. Otherwise, you can enable it with plugins or by adding code snippets to your site’s wp-config.php file.

For more help, you can also use other built-in tools or third-party tools like New Relic (your own license is required) and the free Query Monitor plugin.

Do you have any other questions about how to debug WordPress? Leave a comment and let us know!


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

In a perfect world, you’d never have a single issue that required debugging. But in the real world, you’ll almost certainly run into issues on your WordPress site that require a look under the hood.

To help you do that, WordPress includes its own built-in debug mode and you can also find useful third-party tools to help you debug WordPress.

In this post, we’ll dig into the built-in WordPress debug mode and show you how to enable it. Then, we’ll also share some of the other ways in which you can debug your WordPress site.

Here’s everything that we’ll cover:

  • An introduction to WordPress debug mode and the debug log
  • How to enable WordPress debug mode (three methods)
  • Some other ways to debug WordPress

What Does WP Debug Do?

The core WordPress software is written in PHP, as are plugins and themes.

If you’re having issues with your site, WordPress debug mode can help you find out what’s going wrong by displaying all PHP errors, notices, and warnings.

Once you enable debug mode, you’ll see messages like this whenever there’s an issue (even if it’s not causing immediate problems):

WP_DEBUG example of error on WordPress site

WP_DEBUG example of error on WordPress site

You can then fix the problem or report it to your developer or the theme/plugin’s developer.

What Is the WordPress Debug Log?

When you enable WordPress debug mode by itself, you’ll see messages like the example above on your site in the moment – but those messages won’t be saved anywhere.

If you want to save them, you can also enable the WordPress debug log to save all of those messages and errors to a file on your server.

When enabled by setting the WP_DEBUG_LOG constant to true, WordPress will write all issues to the following file:

wp-content/debug.log

However, you can also specify a custom file path to write the log to a different location on your server.

If you want to save problems to the log but not publicly display them within the HTML of your pages (like the example screenshot above), you can also use the WP_DEBUG_DISPLAY constant to keep debug mode enabled but not display messages on your site.

Typically, you’ll want to combine WP_DEBUG_DISPLAY with WP_DEBUG_LOG.

Ready to debug your #WordPress site? This guide has you covered 🐛Click to Tweet

How to Enable WordPress Debug Mode

To enable WordPress debug mode, you have several options. We’ll cover three methods to enable it:

How to Enable WordPress Debug Mode in MyKinsta

If you host your WordPress site at Kinsta, we built an easy tool that lets you enable the WordPress debug mode without needing to edit your wp-config.php file.

This tool is convenient for being able to quickly enable debug mode and display messages on your site, but it doesn’t let you control the WordPress debug log or whether or not to display messages on live pages. If you want to use just the debug log, you might prefer the plugin method in the next section.

To get started:

  • Open your MyKinsta dashboard.
  • Select the site where you want to enable debugging from the Sites list.
  • Go to the Tools tab in that site’s dashboard.
  • Click Enable under WordPress debugging.

How to enable WordPress debug mode in MyKinsta

How to enable WordPress debug mode in MyKinsta

You can use the tool on both your live and staging environments. Whenever possible, though, we’d recommend using it with your staging environment because enabling WordPress debug mode might display details about your site’s PHP code to visitors (which is confusing for visitors and also a security risk).

When you’re finished, you can disable debug mode by clicking the Disable button in your Kinsta dashboard:

How to disable WordPress debug mode in MyKinsta

How to disable WordPress debug mode in MyKinsta

How to Use a WordPress Debug Plugin

If you’re not hosting at Kinsta, you can also find free WordPress debug plugins that make it easy to enable debug mode. There are several options at WordPress.org, but we recommend the free WP Debugging plugin from Andy Fragen.

WP Debugging WordPress plugin

WP Debugging WordPress plugin

Once you install and activate the plugin, it starts working right away. By default, it sets the following constants to true (that is, it enables the following features):

  • WP_DEBUG – enables debug mode.
  • WP_DEBUG_LOG – saves messages to a log file.
  • SCRIPT_DEBUG
  • SAVEQUERIES

We’ll cover what the last two constants do a little later on in this post.

To configure a few options, you can go to Tools → WP Debugging:

The settings are for the WP Debugging plugin

WP Debugging plugin’s settings

Once you’re finished, make sure to disable the plugin to disable debug mode.

How to Manually Enable WordPress Debug Mode

Finally, you can also enable WordPress debug mode by manually adding the constants to your wp-config.php file.

To get started, connect to your server via FTP and edit the wp-config.php file. By default, this file is in the root folder of your site (unless you moved it for security reasons).

To enable just the basic WordPress debug mode, add the following code snippet above the line that says /* That’s all, stop editing! Happy blogging. */:

// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

You can also use some of the following constants according to your preferences:

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

Once you’re finished, you can either set the constants to false or just remove the snippet to disable debug mode.

Make Sure to Disable Debug Mode in WordPress When You’re Finished

The debug mode is useful when you’re trying to troubleshoot problems with WordPress, but you shouldn’t leave it enabled 24/7 because it can reveal text from your PHP code to website visitors.

We mentioned this above – but this is just a reminder to always disable debug mode when you’re finished troubleshooting.

Other Ways to Debug WordPress

Beyond the built-in debug tool that we featured above, there are several other built-in and third-party tools to help you debug your WordPress site.

Script Debug

SCRIPT_DEBUG is another built-in constant that forces WordPress to use the dev versions of core CSS and JavaScript files instead of the minified versions that it usually loads.

This can be helpful if you’re testing changes to the built-in .js or .css files.

To enable SCRIPT_DEBUG, you can either:

  • Use the free WP Debugging plugin from above, which enables it by default.
  • Add the following constant to your wp-config.php file – define( 'SCRIPT_DEBUG', true );

Database Query Debugging

If you’re having issues with your site’s database, you can enable database query logging using the SAVEQUERIES constant to track:

  • Each database query.
  • The function that called the database query.
  • How long the query took.

To enable query logging, you can either:

  • Use the free WP Debugging plugin from above, which enables it by default.
  • Add the following constant to your wp-config.php file – define( 'SAVEQUERIES', true );

Note: this will impact your site’s performance so try to use it on a staging site whenever possible and disable it as soon as you’re finished.

Query Monitor Plugin

The Query Monitor plugin is a free plugin that’s helpful for debugging a number of different areas in WordPress including:

  • Database queries.
  • PHP errors.
  • Hooks and actions.
  • Block editor blocks.
  • Enqueued scripts and stylesheets.
  • HTTP API calls.
  • User capabilities.

Overall, it’s one of the best WordPress debug tools that you’ll find, which is why it has almost a perfect 5-star rating on over 320 reviews.

Once you install and activate the plugin, you’ll get some new options on the WordPress toolbar that display debug information. When clicked, those options will open a new Query Monitor box that gives you more information:

The Query Monitor plugin

The Query Monitor plugin

For a more detailed look, we have an entire post on how to use the Query Monitor plugin.

New Relic

New Relic is a premium tool for analyzing and debugging your site’s performance. It can help you discover bottlenecks and issues that are affecting your site’s performance.

Kinsta already includes the built-in APM tool. However, you can still use New Relic in the MyKinsta dashboard, provided you have your own license.

Server Logs

Finally, your server logs can also be a useful tool in debugging WordPress.

If you host at Kinsta, you can view all of your server logs from the Logs tab in a site’s dashboard:

Viewing server logs in MyKinsta dashboard

Viewing server logs in MyKinsta dashboard

If you host elsewhere, you’ll need to consult your host’s documentation to learn where you can access your server logs.

It’s time to take a look under the hood and debug your #WordPress site 🐛 This guide has everything you need to get started 💪Click to Tweet

Summary

If you need to debug WordPress, the built-in WordPress debug mode provides a useful way to view PHP errors and notices.

If you host at Kinsta, you can enable it right from your dashboard. Otherwise, you can enable it with plugins or by adding code snippets to your site’s wp-config.php file.

For more help, you can also use other built-in tools or third-party tools like New Relic (your own license is required) and the free Query Monitor plugin.

Do you have any other questions about how to debug WordPress? Leave a comment and let us know!


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

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

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

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

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

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

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

Подробнее

Новости индустрии

Новая цена регистрации доменов

Новая цена регистрации доменов

Администратор домена .IN.UA анонсировал повышение цен на регистрацию доменов in.ua, od.ua, odessa.ua, mk.ua, nikolaev.ua на более чем 40 процентов с 1 октября 2022 года. В связи […]

Подробнее

Themeisle content is free. When you purchase through referral links on our site, we earn a commission. Learn More

From conflicts between WordPress plugins to poorly coded themes and mistakes in custom coding, several problems sound the alarm with website error codes and warnings. Even if you’re not sure what the warnings mean, you must fix them. The first step is learning how to set up a WordPress error log.

As a short explanation, a WordPress error log is exactly what it sounds like: a list of error codes and times that occur on your website.

In this post, we’ll show you how to set up and work with WordPress error logs using the built-in WordPress debug mode.

When should you set up a WordPress error log?

Consider setting up a WordPress error log in the following situations:

  • When you see a blank screen while trying to load your website.
  • When a warning with an error code (401, 404, 500, etc.) appears.
  • If your entire site crashes.
  • If you’re noticing slow website performance.
  • If a plugin or theme isn’t working properly.
  • If you’re curious as to which plugins or themes are causing performance issues.

As is often the case with WordPress, you have two routes to enable error logging with WordPress debug mode:

  1. Manually
  2. With a plugin

We’ll start by showing you the manual method, which just involves adding a few code snippets to your site’s wp-config.php file.

Then, if you want an even simpler option for error logging, we’ll share a free plugin that can get the job done.

Here’s how to do it manually…

Click here if you’d rather jump to the plugin 👈

Step 1: Access and edit the wp-config.php file

If you’re not familiar with your wp-config.php file, it’s one of the core files for holding important configuration details, like the credentials for your site’s database.

To access the wp-config.php file, either download and use an FTP client or a file manager tool in your host’s cPanel.

How to use FTP to connect to WordPress 👈

For this tutorial, we’ll cover the steps to access and edit your wp-config.php file with an FTP client.

In your FTP client, locate the wp-config.php file. This is normally in the root site directory.

access wp-config.php to enable WordPress error log

Upon finding the file, right-click on it and select to edit or view the file. You’ll want to open the file in a text editor.

Step 2: Add a line of code in the wp-config.php file to turn on debug mode

Inside your text editor, search for a line of text that reads Stop editing! Happy blogging.

Place your cursor on the empty line above that line of text.

Paste in the following code:

define( 'WP_DEBUG', true );

If you already notice this line of code in the file, it may currently be set to false. If that’s the case, switch it to true.

Afterward, save the file to your computer and upload the wp-config.php file as an update to your website. This is done through the FTP client.

Great! Now debugging mode is activated for your WordPress site.

Step 3: But wait! I don’t want the errors to show on the frontend of my website

If you took a moment to check your dashboard or the frontend of your site, you may have already seen WordPress errors listed for everyone to see. This may not seem like a big deal if they show up on the WordPress dashboard, but you definitely don’t want the warnings on the frontend.

Not only is publicly displaying errors confusing for your visitors, but it can also be a security risk because it gives them detailed information about your site.

In short, debugging mode is messy when activated by itself.

Therefore, we need to log the errors in WordPress so they are recorded but not publicly displayed.

To log your errors, go back to that exact same wp-config.php file in the text editor.

Look at the debug code you recently pasted into the file. Paste the following new code on the empty line below the debug code:

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

Again, in some situations you might discover that the debug log code is already included. For that, simply make sure that the false at the end of the code is changed to true.

The first line tells WordPress to save error messages to a file called debug.log. The second snippet tells WordPress not to publicly display error messages.

Now, your error messages will be safely saved in the log file, but neither you nor your visitors will have to see error messages while browsing your site.

For a second time, save the wp-config.php file in your file editor and upload it back to your WordPress website.

How to use a WordPress error log plugin

If you don’t feel comfortable working directly with your site’s configuration file, you can also use the free WP Debugging plugin:

As soon as you activate the plugin, it instantly activates WordPress debug mode and enables error logging. It also lets you control whether or not to display debug messages on your site by visiting Tools -> WP Debugging.

Checking your WordPress error logs

We’re assuming you already know the website pages that are alerting you of errors.

You must visit these pages now that the debugging log is configured and ready to store the errors.

Reconnect to your website files using the FTP client. You can also connect via your host’s cPanel.

Go to the /wp-content/ folder.

the wp-content folder contains the WordPress error log file

Open that folder and look for a file called debug.log.

This is the file you created from the previous steps.

What should I do with this debug log file?

The debug.log file is accessible by editing, viewing, or downloading the file. It’s similar to the previous steps, where you might either just preview the file to look at it or open it in a file editor to make changes and save it for later.

Overall, a debug log file is for reference, not for editing. Therefore, you have to sift through the list of errors and warnings to identify what’s wrong with your site, theme, plugins, or code.

error log

For most people, the error log codes mean nothing. If anything, it’s closer to gibberish than English. However, you don’t want to forget about those errors.

Your resolution steps should go like this:

  • You identify an error with the debug log.
  • You find the error code.
  • You look up what that error code means.
  • You utilize a separate guide to fix that error.

How to fix issues that you discover in the error log

Unfortunately, there’s no one-size-fits-all approach to fixing problems that you might discover in your site’s error log.

However, we do have lots of existing posts on how to fix common WordPress errors:

  • A beginner’s guide to WordPress troubleshooting
  • The most common HTTP error codes and how to fix them
  • A guide for checking for plugin compatibility issues
  • What is a 401 error and how do you fix it?
  • How to fix any 404 errors with redirects
  • How to fix the 500 internal server error in WordPress
  • 4 ways to fix an error when establishing a database connection
  • How to fix the white screen of death

If you’re still not sure how to fix the issues in your log file, you might want to hire a WordPress developer to do it for you – here are some tips to find the right developer.

Do you have any questions about how to set up a WordPress error log?

Even looking at bits of code feels intimidating for the average WordPress user.

The good news is that setting up a WordPress error log only takes two small snippets of code.

If you have trouble activating your WordPress error log, or questions on how to fix them, let us know in the comments below!

Free guide

5 Essential Tips to Speed Up
Your WordPress Site

Reduce your loading time by even 50-80%
just by following simple tips.

Download free guide

Каждый уважающий себя разработчик перед началом работы над темой или плагином запустит отладчик. Собственно, WordPress Codex настоятельно рекомендует разработчикам использовать режим WP_DEBUG при работе над кодом, который они собираются выпускать в мир.

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

inet.ws - Powerful VPS around the World!

Отладка кода в WordPress: Как использовать WP_DEBUG

В этой статье я пройдусь по основным имеющимся в наличии средствам отладки для WordPress и покажу вам, насколько они просты в использовании.

Отладка с помощью WP_DEBUG

Основное средство разработки, о котором вам нужно знать — WP_DEBUG.

WP_DEBUG — это константа типа boolean, которая включает режим отладки в WordPress. Она находится в файле wp-config.php в вашей папке WordPress.

Если ее значение установлено «true«, вы увидите извещения PHP на страницах сайта (не столько ошибки, сколько полезные для разработчиков сообщения и WordPress сообщения, в частности информация об устаревших функциях).

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

Чтобы включить WP_DEBUG, просто добавьте следующий код в ваш файл wp-config.php:

define( 'WP_DEBUG', true );

Чтобы отключить режим, просто замените «true» на «false«. Для WP_DEBUG по умолчанию установлено значение false. WP_DEBUG предоставляет удобный способ поиска решения проблем, если что-то с вашим сайтом пошло не так.

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

Записи ошибок с помощью WP_DEBUG_LOG

Другой удобный инструмент — WP_DEBUG_LOG, который может использоваться в сочетании с WP_DEBUG для сохранения всех ошибок в файл debug.log, размещенный в папке /wp-content/ вашего сайта.

Это очень удобная штука, если вы хотите потом просмотреть сообщения.

Чтобы включить запись логов отладки, просто добавьте в ваш файл wp-config.php следующий код:

define('WP_DEBUG_LOG', true);

Выключение отображения ошибок на сайте с помощью WP_DEBUG_DISPLAY

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

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

По умолчанию установлено значение «true«, то есть все ошибки и предупреждения отображаются. Изменив значение на «false«, вы спрячете все ошибки.

Эта константа должна быть использована в сочетании с WP_DEBUG_LOG.

Чтобы использовать эту возможность, просто добавьте в код вашего файла wp-config.php следующую строку:

define('WP_DEBUG_DISPLAY', false);

Все вместе

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

// Turn debugging on
define('WP_DEBUG', true);

// Tell WordPress to log everything to /wp-content/debug.log
define('WP_DEBUG_LOG', true);

// Turn off the display of error messages on your site
define('WP_DEBUG_DISPLAY', false);

// For good measure, you can also add the follow code, which will hide errors from being displayed on-screen
@ini_set('display_errors', 0);

Не забывайте, что WP_DEBUG используется для локальной разработки и не должен использоваться на живых сайтах.

Источник: wpmudev.org

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

inet.ws - Powerful VPS around the World!

Алексей Шевченко

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

Понравилась статья? Поделить с друзьями:
  • Wordpress recaptcha ошибка неверный домен ключа
  • Wordpress duplicator ошибка
  • Wordpress 404 ошибка после переноса сайта
  • Wordpad как включить выделение ошибок
  • Word шаблон ошибка