Admin notice for custom fields in users dashboard

In WordPress, I added some fields in the users dashboard. I made them required but I’d like to display a message if they are empty.

Here is an example (just one field) of what I did :

Read More
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' );

Unfortunately, nothing happens.

I also tried with add_settings_error but I had the same problem.

Can someone give me a hand or just explain to me what I am doing wrong? It would be much appreciated! Thank you very much!

Related posts

Leave a Reply

1 comment

  1. Looks like it’s too late to add the admin_notice. An alternative is to use the action hook load-$page (that runs at the very beginning of a page load) and check if the user meta is empty. If so, trigger the notice.

    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');
    }