高级管理文档

WordPress 中的调试

💡 云策文档标注

概述

本文档介绍了 WordPress 中用于调试 PHP 代码的特定系统,包括 WP_DEBUG 等常量,旨在简化调试过程并提高代码质量和互操作性。它面向开发者,提供了从基础配置到高级自定义的调试工具。

关键要点

  • WordPress 提供 WP_DEBUG、WP_DEBUG_LOG、WP_DEBUG_DISPLAY 等常量来启用调试模式、日志记录和错误显示控制。
  • 调试工具主要用于本地测试和暂存环境,不建议在生产站点使用,以避免性能和安全问题。
  • 启用 WP_DEBUG 会显示所有 PHP 错误、警告、通知以及已弃用函数和参数的提示,有助于识别和修复代码问题。
  • 可以使用自定义函数(如 write_log)来格式化记录非错误信息,但建议避免在 functions.php 中添加以避免维护问题。
  • 其他相关常量包括 SCRIPT_DEBUG(用于加载开发版核心文件)和 SAVEQUERIES(用于保存数据库查询),后者可能影响性能。
  • WordPress 社区提供了如 Debug Bar 等调试插件,可以增强调试功能,显示查询、缓存等内部信息。

代码示例

// 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
define( 'SCRIPT_DEBUG', true );

注意事项

  • 在修改网站前,请确保使用暂存环境或备份站点。
  • 调试代码应插入 wp-config.php 文件中的特定位置(在 /* That's all, stop editing! Happy blogging. */ 之前)。
  • 设置常量时,布尔值 true 和 false 不应加引号,否则会被解释为字符串而非布尔值。
  • SAVEQUERIES 可能对站点性能产生影响,调试后应及时关闭。

📄 原文内容

Debugging PHP code is part of any project, but WordPress comes with specific debugging systems designed to simplify the process as well as standardize code across the core, plugins, and themes. This page describes the various debugging tools available in WordPress and how to be more productive in your coding, as well as increasing the overall quality and interoperability of your code.

For non-programmers or general users, these options can be used to show detailed information about errors.

NOTE: Before making any modifications to your website, verify that you have either utilized a staging environment or taken an appropriate backup of your site.

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.

WP_DEBUG

WP_DEBUG is a PHP constant (a permanent global variable) that can be used to trigger the “debug” mode throughout WordPress. It is assumed to be false by default, and is usually set to true in the wp-config.php file on development copies of WordPress.

// This enables debugging.
define( 'WP_DEBUG', true );
// This disables debugging.  
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 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.

Custom PHP Debugging

If it is necessary to log non-error information for debugging purposes, PHP does offer the error_log function for this purpose. However, this method does not provide properly formatted output by default.

To address this, you may add another function on your site to handle formatting, either by creating a custom plugin or using a snippet with some code snippets plugin. The function will act as a wrapper for the error_log using print_r to format arrays and objects correctly before logging them.

Below is an example function that requires WP_DEBUG to be enabled.

function write_log( $data ) {
    if ( true === WP_DEBUG ) {
        if ( is_array( $data ) || is_object( $data ) ) {
            error_log( print_r( $data, true ) );
        } else {
            error_log( $data );
        }
    }
}

Usage Examples:

write_log( 'DEBUG TEXT' );
write_log( $variable );

Note: It is not recommended to add custom code like the above example in functions.php to avoid maintenance, security, performance, compatibility, and code organization issues.

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. 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 a log file using PHP’s built in error_log() function, which can be useful for instance when debugging Ajax events.

When set to true, the log is saved to debug.log in the content directory (usually wp-content/debug.log) within your site’s file system. Alternatively, you can set it to a valid file path to have the file saved elsewhere.

define( 'WP_DEBUG_LOG', true );

-or-

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

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 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 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. The default is false.

define( 'SCRIPT_DEBUG', true );

SAVEQUERIES

The SAVEQUERIES definition saves database queries to an array, which can then be displayed to help analyze those queries. When the constant is set to true, it causes each query to be saved along with the time it took to execute and the function that 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.

Debugging Plugins

There are many debugging plugins for WordPress that show more information about the internals, either for a specific component or in general.

For example, Debug Bar adds a debug menu to the admin bar that shows query, cache, and other helpful debugging information. When WP_DEBUG is enabled, it also tracks PHP Warnings and Notices to make them easier to find.