Anevi.com
Debugging in WordPress

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

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

WP_DEBUG #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 #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.

Top ↑

Deprecated Functions and Arguments #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.

Top ↑

WP_DEBUG_LOG #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 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 filesystem. 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.

Top ↑

WP_DEBUG_DISPLAY #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.

Top ↑

SCRIPT_DEBUG #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. Default is false.

define( 'SCRIPT_DEBUG', true );

Top ↑

SAVEQUERIES #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.

Top ↑

Example wp-config.php for 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.

Top ↑

Debugging Plugins #Debugging Plugins

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

MySQL: [solución] Unknown collation: ‘utf8mb4_unicode_520_ci’

Obtenido del Blog Oficial de Bufa, publicación original por Jorge Maiden – 17 septiembre 2018.

Solución al error: #1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ que nos sale al importar algún archivo sql que se ha creado con una versión de MySQL más reciente que la del actual servidor en en que estamos importando.

Error muy común cuando creamos por ejemplo un wordpress en local y nos decidimos a importar el sql al servidor destino.

Basta con abrir ese archivo sql y buscar todas las apariciones de:

utf8mb4_unicode_520_ci

Y reemplazarlo por:

utf8mb4_unicode_ci

Cómo importar y exportar bases de datos en MySQL o MariaDB

Obtenido del Blog Oficial de Stackscale – 03 abril 2017.

Created with GIMP

Hoy en día, se ha vuelto prácticamente imprescindible, realizar copias de seguridad de nuestros sitios y aplicaciones web. Cuando hablamos de backups, no solo nos referimos a los archivos que forman parte de la web, sino también a la base de datos. Una vez que hemos realizado nuestra copia de respaldo, podemos restaurarla en cualquier momento en caso de sufrir algún tipo de hackeo o pérdida de información.

En nuestra entrada de hoy, nos centraremos en el proceso de copia de seguridad de bases de datos MySQL y MariaDB, así como en los pasos a seguir para su restauración. Una tarea sencilla cuyos pasos podréis descubrir a continuación.

Requisitos previos

Antes de nada, será interesante conocer los requisitos que necesitaremos para poder importar o exportar una base de datos MySQL o MariaDB:

  • Acceso al servidor donde está instalado MySQL o MariaDB.
  • El nombre de la base de datos, el usuario y la contraseña de acceso a la base de datos.

Exportando la base de datos

Para realizar la exportación de la base de datos, tendremos que hacer uso del comando “mysqldump” que utilizaremos desde consola. Una vez que hayamos realizado el backup, el archivo generado lo podremos mover de forma sencilla.

Para realizar la exportación de la base de datos, deberemos ejecutar lo siguiente:

mysqldump -u username -p database_name > data-dump.sql
  • username hace referencia al nombre del usuario de la base de datos.
  • database_name tendrá que ser sustituido por el nombre de la base de datos.
  • data-dump.sql es el archivo que se generará con toda la información de la base de datos.

Ese comando no producirá ningún tipo de salida visual. De todas formas, podemos inspeccionar el archivo generado para asegurarnos de que se trata de una copia SQL utilizando la siguiente instrucción.

head -n 5 data-dump.sql

Ese comando nos deberá devolver algo parecido a lo que os dejamos a continuación.

-- MySQL dump 10.13  Distrib 5.7.16, for Linux (x86_64)
--
-- Host: localhost    Database: database_name
-- ------------------------------------------------------
-- Server version       5.7.16-0 ubuntu 0.16.04.1

Importando la base de datos

Para importar un volcado de MySQL o MariaDB, lo primero que deberemos hacer será crearnos la base de datos donde haremos la importación. Para hacer esto, si no tenemos ningún gestor de bases de datos, tendremos que conectarnos al servidor de bases de datos como usuario root.

mysql -u root –p

Esto hará que se abra el Shell de MySQL o MariaDB. A continuación, crearemos la base de datos.

mysql> CREATE DATABASE new_database;

Si todo ha ido correcto, deberás ver una salida parecida a lo siguiente.

Query OK, 1 row affected (0.00 sec)

Cuando ya la hayamos creado, tendremos que salir de ese Shell. Para ello, pulsaremos CTRL+D. Cuando estemos en la línea de comandos normal, será el momento de lanzar el comando que se encargará de realizar la importación de la base de datos.

mysql -u username -p new_database < data-dump.sql
  • username será el nombre del usuario con acceso a la base de datos
  • new_database es el nombre de la base de datos donde se realizará la importación
  • data-dump.sql es el nombre del archivo que contiene todas las instrucciones sql que vamos a importar.

Si durante el proceso de importación se produjera algún tipo de error, estos se mostrarían por pantalla.

Como habéis podido leer, el proceso de exportación e importación de una base de datos MySQL o MariaDB, es un proceso muy sencillo que se puede realizar mediante unos sencillos pasos.