Last active
July 21, 2021 16:37
-
-
Save wpscholar/9004667 to your computer and use it in GitHub Desktop.
Merge multiple WP_Error objects together
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For anyone hitting this page, as of WordPress 5.6 WP_Error allows merging objects together. See https://core.trac.wordpress.org/ticket/38777