Log Slow Outgoing HTTP Requests
Times every request your site makes to other servers (update checks, APIs, license servers) and records the ones slower than a second under Tools > Slow HTTP Calls, so you can find what is holding up page loads.
Opens WPIDE on
Code
// Requests slower than this many seconds are logged.
$wpide_http_slow = 1.0;
add_filter( 'pre_http_request', function ( $pre, $args, $url ) {
$GLOBALS['wpide_http_timers'][ md5( $url ) ] = microtime( true );
return $pre;
}, 1, 3 );
add_action( 'http_api_debug', function ( $response, $context, $class, $args, $url ) use ( $wpide_http_slow ) {
$key = md5( $url );
if ( empty( $GLOBALS['wpide_http_timers'][ $key ] ) ) {
return;
}
$time = microtime( true ) - $GLOBALS['wpide_http_timers'][ $key ];
unset( $GLOBALS['wpide_http_timers'][ $key ] );
if ( $time < $wpide_http_slow ) {
return;
}
$parts = wp_parse_url( $url );
$clean = ( isset( $parts['host'] ) ? $parts['host'] : '' ) . ( isset( $parts['path'] ) ? $parts['path'] : '' );
$where = is_admin() ? 'admin' : ( wp_doing_cron() ? 'cron' : 'front' );
$log = (array) get_option( 'wpide_slow_http', array() );
$log[] = array(
'url' => $clean,
'method' => isset( $args['method'] ) ? $args['method'] : 'GET',
'time' => round( $time, 2 ),
'status' => is_wp_error( $response ) ? $response->get_error_message() : wp_remote_retrieve_response_code( $response ),
'where' => $where,
'when' => time(),
);
update_option( 'wpide_slow_http', array_slice( $log, -100 ), false );
}, 10, 5 );
add_action( 'admin_menu', function () {
add_management_page( 'Slow HTTP Calls', 'Slow HTTP Calls', 'manage_options', 'wpide-slow-http', function () {
$log = array_reverse( (array) get_option( 'wpide_slow_http', array() ) );
echo '<div class="wrap"><h1>Slow HTTP Calls</h1><table class="widefat striped"><thead><tr><th>When</th><th>Request</th><th>Time</th><th>Result</th><th>Context</th></tr></thead><tbody>';
if ( ! $log ) {
echo '<tr><td colspan="5">No slow requests logged yet.</td></tr>';
}
foreach ( $log as $row ) {
printf( '<tr><td>%s</td><td><code>%s %s</code></td><td>%ss</td><td>%s</td><td>%s</td></tr>', esc_html( human_time_diff( (int) $row['when'] ) . ' ago' ), esc_html( $row['method'] ), esc_html( $row['url'] ), esc_html( $row['time'] ), esc_html( (string) $row['status'] ), esc_html( $row['where'] ) );
}
echo '</tbody></table></div>';
} );
} );
Notes
Keeps the latest 100 slow calls; URLs are stored without their query strings so API keys are not logged.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.