WordPress: introduzione alla classe WP_Error

WordPress: introduzione alla classe WP_Error

Questo articolo è un'introduzione alla classe WP_Error di WordPress. Come suggerisce il suo nome, questa classe gestisce gli errori e le eccezioni in WordPress.

Consideriamo il seguente codice:


global $post;
$id = $post->ID;

$terms = get_the_terms( $id, 'nometassonomia' );

if ( $terms && ! is_wp_error( $terms ) ) {

	foreach( $terms as $term ) {
		echo $term->name . "\n";
	}
}

La sezione Returns (valori di ritorno) della documentazione di WordPress per la funzione get_the_terms() afferma che:

Array of term objects on success; false if the post contains no terms from the given taxonomy; false if the post doesn't exist; and a Class_Reference/WP_Error object if an invalid taxonomy is entered.

La funzione is_wp_error() verifica che il valore restituito sia o meno un'instanza della classe core WP_Error. Questa classe può essere usata anche per gestire i nostri errori:


function my_func( $param ) {
	if( !$param ) {
		return new WP_Error( 'codice-errore', 'Messaggio di errore' );
	}
}

$return = my_func();
if( is_wp_error( $return ) ) {
    echo $return->get_error_message(); // 'Messaggio di errore'
}

Il costruttore della classe accetta tre parametri:

  1. una stringa rappresentante il codice dell'errore
  2. il messaggio di errore associato al codice
  3. i dati associati all'errore sotto forma di array

Potete trovare maggiori informazioni su questa classe nella documentazione ufficiale.

Torna su