用户面板中自定义字段的管理通知


Admin notice for custom fields in users dashboard

在Wordpress中,我在用户面板中添加了一些字段。我要求它们,但如果它们是空的,我想显示一条消息。

以下是我所做的一个示例(仅一个字段(:

function my_admin_notice() { ?>
    <div class="error">
        <p><?php _e( 'Error!', 'user_street' ); ?></p>
    </div>
    <?php
}
function save_extra_user_profile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) ) { 
        return false;
    }
    if (!empty($_POST['user_street'])) {
        update_user_meta( $user_id, 'user_street', $_POST['user_street'] );
    }
    else {
        add_action('admin_notices', 'my_admin_notice');
        return false;
    }
}
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

不幸的是,什么都没发生。

我也尝试了add_settings_error,但我遇到了同样的问题。

有人能帮我一把吗?或者只是向我解释我做错了什么?非常感谢!非常感谢!

添加admin_notice似乎为时已晚。另一种选择是使用动作挂钩load-$page(在页面加载的最开始运行(并检查用户元是否为空。如果是,则触发通知。

add_action( 'load-profile.php', 'notice_so_23373245' );
add_action( 'load-user-edit.php', 'notice_so_23373245' );
function notice_so_23373245() 
{
    // Check to see if page is user-edit or profile
    $user = isset( $_GET['user_id'] ) ? $_GET['user_id'] : get_current_user_id();
    if( empty( get_user_meta( $user, 'user_street' ) ) )
        add_action('admin_notices', 'my_admin_notice');
}