Merging Multiple `WP_Error` Objects into One Object

Let’s say you have a function that does two things:

function my_func() {
    $a = a();
    $b = b();
    if( is_wp_error( $a ) || is_wp_error( $b ) ) { return FALSE; }
    return TRUE;
}

That’s a little cumbersome, because if it returns `FALSE`, I’m left unable to tell which failed: `$a` or `$b`, or both.

Here’s what we can do instead:

function my_func() {
	$a = a();
	$b = b();
	$maybe_errors = new WP_Multi_Error( array( $a, $b ) );
	if( $maybe_errors -> is_wp_error() ) {
		return $maybe_errors -> get_error();
	} else {
		return TRUE;
	}
}

So what happened there?

I’ve got a custom class, `WP_Multi_Error`, that extends `WP_Error`. You can pass it an array with any number of members, of any type. It loops through them and, for any that are error objects, it merges them together into one error.

Here’s the gist: