Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Дебаг в WordPress

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

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

WP_DEBUG

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

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

Note: The true and false values in the example are not surrounded by apostrophes (') because they are boolean (true/false) values. If you set constants to 'false', they will be interpreted as true because the quotes make it a string rather than a boolean.

It is not recommended to use WP_DEBUG or the other debug tools on live sites; they are meant for local testing and staging installs.

PHP Errors, Warnings, and Notices

Enabling WP_DEBUG will cause all PHP errors, notices and warnings to be displayed. This is likely to modify the default behavior of PHP which only displays fatal errors and/or shows a white screen of death when errors are reached.

Showing all PHP notices and warnings often results in error messages for things that don't seem broken, but do not follow proper data validation conventions inside PHP. These warnings are easy to fix once the relevant code has been identified, and the resulting code is almost always more bug-resistant and easier to maintain.

Deprecated Functions and Arguments

Enabling WP_DEBUG will also cause notices about deprecated functions and arguments within WordPress that are being used on your site. These are functions or function arguments that have not been removed from the core code yet but are slated for deletion in the near future. Deprecation notices often indicate the new function that should be used instead.

WP_DEBUG_LOG

WP_DEBUG_LOG is a companion to WP_DEBUG that causes all errors to also be saved to a debug.log log file inside the /wp-content/ directory. This is useful if you want to review all notices later or need to view notices generated off-screen (e.g. during an AJAX request or wp-cron run).

Note that this allows you to write to /wp-content/debug.log using PHP's built in error_log() function, which can be useful for instance when debugging AJAX events.

define( 'WP_DEBUG_LOG', true );

Note: for WP_DEBUG_LOG to do anything, WP_DEBUG must be enabled (true). Remember you can turn off WP_DEBUG_DISPLAY independently.

WP_DEBUG_DISPLAY

WP_DEBUG_DISPLAY is another companion to WP_DEBUG that controls whether debug messages are shown inside the HTML of pages or not. The default is 'true' which shows errors and warnings as they are generated. Setting this to false will hide all errors. This should be used in conjunction with WP_DEBUG_LOG so that errors can be reviewed later.

define( 'WP_DEBUG_DISPLAY', false );

Note: for WP_DEBUG_DISPLAY to do anything, WP_DEBUG must be enabled (true). Remember you can control WP_DEBUG_LOG independently.

SCRIPT_DEBUG

SCRIPT_DEBUG is a related constant that will force WordPress to use the "dev" versions of some core CSS and JavaScript files rather than the minified versions that are normally loaded. This is useful when you are testing modifications to any built-in .js or .css files. Some scripts (notably the core jquery package) do not honor SCRIPT_DEBUG. Default is false.

define( 'SCRIPT_DEBUG', true );

SAVEQUERIES

The SAVEQUERIES definition saves the database queries to an array and that array can be displayed to help analyze those queries. The constant defined as true causes each query to be saved, how long that query took to execute, and what function called it.

define( 'SAVEQUERIES', true );

The array is stored in the global $wpdb->queries.

NOTE: This will have a performance impact on your site, so make sure to turn this off when you aren't debugging.

Example wp-config.php for Debugging

The following code, inserted in your wp-config.php file, will log all errors, notices, and warnings to a file called debug.log in the wp-content directory. It will also hide the errors so they do not interrupt page generation.

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

// 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 );

// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );

NOTE: You must insert this BEFORE /* That's all, stop editing! Happy blogging. */ in the wp-config.php file

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

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

doing_it_wrong()

When you're making a mistake with your code in WordPress, you may see a message like

Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) 

Messages like above are automatically trigged by WordPress' doing_it_wrong() function and recommends you to read this page.

The causes of the message to appear are numerous and the previous error message should mention some more detail why the error was caused.

One common reason is that you're not calling/loading (java)scripts properly. When calling scripts, use an action hook to load them at the proper time. See this example to learn how to call an action hook with your scripts.


Дополнительные Ресурсы