How are bulk actions handled in custom list table classes?

The question:

I’m working on a custom data table to display in the WordPress dashboard. The table populates from a database table I built in a plugin.

I’ve been using the provided WordPress Custom List Table example for most of my coding questions in this area, but the example doesn’t have anything for handling bulk actions. Here is the link for the documented example: http://wordpress.org/extend/plugins/custom-list-table-example/

For processing the bulk actions, the example only provides this:

    function process_bulk_action() {

    //Detect when a bulk action is being triggered...
    if( 'delete'===$this->current_action() ) {

        wp_die('Items deleted!');
    }

}

I want to know how to pull the items selected for the action so I can delete them or edit their database entries accordingly.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Assuming you’re using the standard column_cb() function, the list table will pass the IDs of the selected rows in an array in $_GET, labeled as whatever you assigned to ‘singular’ in the list table’s constructor.

Here’s a typical column_cb():

function column_cb($item){
        return sprintf(
            '<input type="checkbox" name="%1$s[]" value="%2$s" />',
            /*$1%s*/ $this->_args['singular'],  //Let's simply repurpose the table's singular label ("video")
            /*$2%s*/ $item->id             //The value of the checkbox should be the record's id
        );
    }

For example, let’s say I have a list table that displays videos. The constructor would look like:

function __construct(){
        global $status, $page;

        //Set parent defaults
        parent::__construct( array(
            'singular'  => 'video',     //singular name of the listed records
            'plural'    => 'videos',    //plural name of the listed records
            'ajax'      => false        //does this table support ajax?
        ) );

    }

So, if you check three rows in the list table, select “Delete” from the bulk actions list, and hit apply, you could access the selected rows by using $_GET[‘video’].

function process_bulk_action() {

        //Detect when a bulk action is being triggered...
        if( 'delete'===$this->current_action() ) {
            foreach($_GET['video'] as $video) {
                //$video will be a string containing the ID of the video
                //i.e. $video = "123";
                //so you can process the id however you need to.
                delete_this_video($video);
            }
        }

    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment