出错时停止运行用户删除

时间:2021-01-26 作者:Greeso

我正在编写以下代码,以便在通过管理区域删除用户之前进行一些清理

function delete_user_custom_data ($user_id) {
    
    $result = do_some_cleanp($user_id); // The do_some_cleanp() function returns true on success and false on failure
    
    if ($result == false) {
        ?>
        <div class="notice notice-warning is-dismissible">
            <p>There was a problem</p>
        </div>
        <?php
    }
}

add_action(\'delete_user\', \'delete_user_custom_data\');
我喜欢做的是prevent 如果“delete\\u user”操作函数中的代码未成功,则从运行中删除用户。我该怎么做?

谢谢

1 个回复
SO网友:Greeso

在问题的评论部分与@CelsoBessa讨论后,我想出了这个解决方案

function display_admin_notices () {
    
    // NOTE: Maybe code should be added here to ensure you are displaying those notices only for certain admin pages
    
    if (isset($_GET[\'update\'])) {
        
        switch ($_GET[\'update\']) {
            
            case NOTICE__ERROR:
                $type = \'notice-error\';
                break;
            
            case NOTICE__WARNING:
                $type = \'notice-warning\';
                break;
            
            case NOTICE__SUCCESS:
                $type = \'notice-success\';
                break;
            
            case NOTICE__INFO:
                $type = \'notice-info\';
                break;
        }
        
        ?>
        <div class="notice is-dismissible">
            <p><?php echo stripslashes($_GET[\'message\']); ?></p>
        </div>
        <?php

    }

}

function delete_user_custom_data ($user_id) {
    
    $result = do_some_cleanp($user_id); // The do_some_cleanp() function returns true on success and false on failure
    
    if ($result == false) {
        $query_vars = array (
            \'message\'   => rawurlencode(\'There was a problem.\'),
            \'update\'    => NOTICE__ERROR
        );
        
        $redirect_url = add_query_arg(
            $query_vars,
            network_admin_url(\'users.php\')
        );
        
        wp_safe_redirect($redirect_url);
        exit;
    }
}

// Global constants (within the namespace, but I did not add the namespace to simplify the answer)
const NOTICE__ERROR     = 0;
const NOTICE__WARNING   = 1;
const NOTICE__SUCCESS   = 2;
const NOTICE__INFO      = 3;

add_action(\'admin_notices\', \'display_admin_notices\');
add_action(\'delete_user\', \'delete_user_custom_data\');