Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Last active July 21, 2021 16:37
Show Gist options
  • Save wpscholar/9004667 to your computer and use it in GitHub Desktop.
Save wpscholar/9004667 to your computer and use it in GitHub Desktop.
Merge multiple WP_Error objects together
<?php
/**
* Merge multiple WP_Error objects together
*
* @return WP_Error
*/
function 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;
}
/**
* @var WP_Error $wp_error
*/
$error_codes = $wp_error->get_error_codes();
foreach( $error_codes as $error_code ) {
// Merge error messages
$error_messages = $wp_error->get_error_messages( $error_code );
foreach( $error_messages as $error_message ) {
$wp_error_merged->add( $error_code, $error_message );
}
// Merge error data
$error_data = $wp_error->get_error_data( $error_code );
if( $error_data ) {
$prev_error_data = $wp_error_merged->get_error_data( $error_code );
if( ! empty( $prev_error_data ) && is_array( $error_data ) && is_array( $prev_error_data ) ) {
$wp_error_merged->add_data( array_merge( $prev_error_data, $error_data ), $error_code );
} else {
$wp_error_merged->add_data( $error_data, $error_code );
}
}
}
}
return $wp_error_merged;
}
@wpscholar
Copy link
Author

@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