Skip to content

Instantly share code, notes, and snippets.

@mjangda
Created June 26, 2013 20:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mjangda/5871525 to your computer and use it in GitHub Desktop.
Save mjangda/5871525 to your computer and use it in GitHub Desktop.
Merge multiple WP_Error objects together.
<?php
function wpcom_wp_error_merge() {
$wp_error_merged = new WP_Error();
$wp_errors = func_get_args();
foreach ( $wp_errors as $wp_error ) {
if ( ! is_wp_error( $wp_error ) )
continue;
foreach ( $wp_error as $key => $errors ) {
foreach ( $errors as $error ) {
$wp_error_merged->add( $key, $error );
}
if ( isset( $wp_error->error_data[ $key ] ) ) {
$wp_error_merged->add_data( $wp_error->error_data[ $key ], $key );
}
}
}
return $wp_error_merged;
}
@wpscholar
Copy link

Thanks for sharing this code! I was needing something like this, but your code doesn't take into account preserving the error keys since your iterator is using the numeric index as the key. I created a more robust solution based on your original code: https://gist.github.com/woodent/9004667.

@stephanethomas
Copy link

@wpscholar, your link doesn't lead anywhere. I guess it should be that one.

@thefrosty
Copy link

For anyone hitting this page, as of WordPress 5.6 WP_Error allows merging objects together. See https://core.trac.wordpress.org/ticket/38777

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment