Add a button to users.php

Okay.. you COULD add a button like you mentioned; but I think this is going to require a lot more code. The users.php page is using the WP List Table class.. which means we can hook into the bulk actions and add our custom value there.

So, let’s create a function to add a new value into the bulk actions dropdown box:

add_action('admin_footer', 'my_user_del_button');
function my_user_del_button() {
    $screen = get_current_screen();
    if ( $screen->id != "users" )   // Only add to users.php page
        return;
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('<option>').val('del_user_meta').text('Delete User Meta').appendTo("select[name="action"]");
        });
    </script>
    <?php
}

This will add the “Delete User Meta” value to the bulk actions dropdown box. Now, we need a function to actually process the data being sent:

add_action('load-users.php', 'my_users_page_loaded');
function my_users_page_loaded() {
    if(isset($_GET['action']) && $_GET['action'] === 'del_user_meta') {  // Check if our custom action was selected
        $del_users = $_GET['users'];  // Get array of user id's which were selected for meta deletion
        if ($del_users) {  // If any users were selected
            foreach ($del_users as $del_user) {
            delete_user_meta($del_user, 'YOUR_METADATA_KEY_TO_BE_REMOVED');  // Change this meta key to match the key you would like to delete; or an array of keys.
            }
        }
    }
}

Here, we iterate through each of the users we placed a checkmark next to. Then, it will delete the meta_key you specified for each of those selected users.

NOTE: You need to change the YOUR_METADATA_KEY_TO_BE_REMOVED string to the actual name of the meta_key you would like to delete. If you are wanting to delete more than a single meta key, you will need to add multiple delete_user_meta() functions.

Leave a Comment