How are bulk actions handled in custom list table classes?

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

    }

Leave a Comment

tech