WP_Site_Health::can_perform_loopback()publicWP 5.2.0

Runs a loopback test on the site.

Loopbacks are what WordPress uses to communicate with itself to start up WP_Cron, scheduled posts, make sure plugin or theme edits don't cause site failures and similar.

Method of the class: WP_Site_Health{}

Hooks from the method

Return

Object. The test results.

Usage

$WP_Site_Health = new WP_Site_Health();
$WP_Site_Health->can_perform_loopback();

Changelog

Since 5.2.0 Introduced.

WP_Site_Health::can_perform_loopback() code WP 6.6.2

public function can_perform_loopback() {
	$body    = array( 'site-health' => 'loopback-test' );
	$cookies = wp_unslash( $_COOKIE );
	$timeout = 10; // 10 seconds.
	$headers = array(
		'Cache-Control' => 'no-cache',
	);
	/** This filter is documented in wp-includes/class-wp-http-streams.php */
	$sslverify = apply_filters( 'https_local_ssl_verify', false );

	// Include Basic auth in loopback requests.
	if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
		$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
	}

	$url = site_url( 'wp-cron.php' );

	/*
	 * A post request is used for the wp-cron.php loopback test to cause the file
	 * to finish early without triggering cron jobs. This has two benefits:
	 * - cron jobs are not triggered a second time on the site health page,
	 * - the loopback request finishes sooner providing a quicker result.
	 *
	 * Using a POST request causes the loopback to differ slightly to the standard
	 * GET request WordPress uses for wp-cron.php loopback requests but is close
	 * enough. See https://core.trac.wordpress.org/ticket/52547
	 */
	$r = wp_remote_post( $url, compact( 'body', 'cookies', 'headers', 'timeout', 'sslverify' ) );

	if ( is_wp_error( $r ) ) {
		return (object) array(
			'status'  => 'critical',
			'message' => sprintf(
				'%s<br>%s',
				__( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ),
				sprintf(
					/* translators: 1: The WordPress error message. 2: The WordPress error code. */
					__( 'Error: %1$s (%2$s)' ),
					$r->get_error_message(),
					$r->get_error_code()
				)
			),
		);
	}

	if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
		return (object) array(
			'status'  => 'recommended',
			'message' => sprintf(
				/* translators: %d: The HTTP response code returned. */
				__( 'The loopback request returned an unexpected http status code, %d, it was not possible to determine if this will prevent features from working as expected.' ),
				wp_remote_retrieve_response_code( $r )
			),
		);
	}

	return (object) array(
		'status'  => 'good',
		'message' => __( 'The loopback request to your site completed successfully.' ),
	);
}