<?php
/**
* Plugin Name: Medición WP - Server Timing
* Description: Añade cabeceras Server-Timing y log para estimar TTFB y coste de partes clave.
*/
// punto de inicio lo más pronto posible
$GLOBALS['__t0'] = microtime(true);
// Opcional: mide consultas SQL
if ( ! defined('SAVEQUERIES') ) {
define('SAVEQUERIES', true);
}
/** Marca un hito en Server-Timing */
function mt_mark($name) {
if (!headers_sent()) {
$t = (microtime(true) - $GLOBALS['__t0']) * 1000; // ms
header(sprintf("Server-Timing: %s;desc=\"%s\";dur=%.2f", $name, $name, $t), false);
}
}
// Marcas útiles en el ciclo
add_action('plugins_loaded', function(){ mt_mark('plugins_loaded'); });
add_action('after_setup_theme', function(){ mt_mark('after_setup_theme'); });
add_action('init', function(){ mt_mark('init'); });
add_action('template_redirect', function(){ mt_mark('template_redirect'); });
add_action('wp', function(){ mt_mark('wp'); });
// Medición final al apagar (aprox TTFB si el servidor envía al final del buffer)
add_action('shutdown', function () {
$total = (microtime(true) - $GLOBALS['__t0']) * 1000;
if (!headers_sent()) {
header(sprintf("Server-Timing: total;desc=\"total\";dur=%.2f", $total), false);
}
if (defined('SAVEQUERIES') && SAVEQUERIES && !empty($GLOBALS['wpdb']->queries)) {
$db_ms = 0;
foreach ($GLOBALS['wpdb']->queries as $q) { $db_ms += (float)$q[1] * 1000; }
error_log(sprintf('[WP] total=%.2fms; DB=%.2fms; queries=%d',
$total, $db_ms, count($GLOBALS['wpdb']->queries)));
} else {
error_log(sprintf('[WP] total=%.2fms', $total));
}
});