Add a button to users.php

I am working on a plugin that adds meta data for each user to the users.php table that is displayed by adding columns. I have that done but I would like to also add a button that will delete the meta data of the users when pressed. I’m not sure how I can add it. I would like it to be to the right of the ‘change’ button. I thought that the behavior would be to reload the page but when it does, I’ll have it delete the meta data for each user.

Where would I start to add that button to the page? Is this the best way to go about this?

Thanks!

2 Answers
2

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