由于用户名可能有多个错误,因此接受的答案可以删除我们希望保留的错误。例如,输入用户名123现在将通过,而它可能仍然会给出错误消息\'Sorry, usernames must have letters too!\'
已修改示例代码以修复此问题:
/* Plugin Name: Allow short user names for multi site. */
add_filter( \'wpmu_validate_user_signup\', \'wpse_59760_short_user_names\' );
/**
* Allow very short user names.
*
* @wp-hook wpmu_validate_user_signup
* @param array $result
* @return array
*/
function wpse_59760_short_user_names( $result )
{
$error_name = $result[ \'errors\' ]->get_error_messages( \'user_name\' );
if ( empty ( $error_name )
or false===$key=array_search( __( \'Username must be at least 4 characters.\' ), $error_name)
)
{
return $result;
}
// only remove the error we are disabling, leaving all others
unset ( $result[ \'errors\' ]->errors[ \'user_name\' ][$key] );
/**
* re-sequence errors in case a non sequential array matters
* e.g. if a core change put this message in element 0 then get_error_message() would not behave as expected)
*/
$result[ \'errors\' ]->errors[ \'user_name\' ] = array_values( $result[ \'errors\' ]->errors[ \'user_name\' ] );
return $result;
}
EDIT:这在WordPress版本3.9.6及4.2中都适用
请注意,这在WordPress 4.0或4.1中不起作用,因为https://core.trac.wordpress.org/ticket/22234 将错误作为专用变量。虽然提供了一个“向后兼容”的神奇\\uu get方法,但对于数组,它返回一个数组的副本(不是对原始数组的引用),然后该副本就不可编辑了。如果打开了WP\\u DEBUG,您将收到一条PHP通知,上面写着“通知:间接修改重载属性WP\\u Error::$errors在第xxx行的/path/to/plugin中无效”,否则代码会自动失败并且无效。
它在版本4.2中再次工作,因为https://core.trac.wordpress.org/ticket/30891 恢复了对WP\\u Error和core中许多其他位置的更改,尽管这样的代码无法正常工作。
对于WordPress>=4.1,它为我们提供了一种删除方法,这同样适用:
function wpse_59760_short_user_names( $result )
{
$error_name = $result[ \'errors\' ]->get_error_messages( \'user_name\' );
if ( empty ( $error_name )
or false===$key=array_search( __( \'Username must be at least 4 characters.\' ), $error_name)
)
{
return $result;
}
// remember any error data
$data = $result[ \'errors\' ]->get_error_data( \'user_name\' );
// remove all user name errors
$result[ \'errors\' ]->remove( \'user_name\' );
// add back in any other user name errors we want to keep
foreach ( $error_name as $index=>$message ) {
if ( $index !== $key )
$result[ \'errors\' ]->add( \'user_name\', $message );
}
// restore any user_name error data that was present
if ( !empty( $data ) )
$result[ \'errors\' ]->add_data( $data, \'user_name\' );
return $result;
}