How to add row actions to custom WordPress tables with WP_List_Table

Adding new tables to WordPress admin is quickly done by extending the WP_List_Table class. This article assumes you have extended the class, created your columns and now want to add row actions.

The project I’m currently working on is a plugin to manage WooCommerce products. For this I created my own table class. The first column should show row actions to edit and view the product.

In WP_List_Table, the content for each cell is handled by the function column_default(). By over-riding this function in my own class I can define what content is being called in.

In addition to this default setting, WordPress also has a simple way of definining content for an individual column by creating a function in format column_{name} where {name} is the name of the column. For a column with name “id” this would be:

public function column_id(  $item ) {

}

The object $item only has one property, the id:

$item->id

Now to add a custom row action I just need to add a div with class “row-actions” to my column:

public function column_id(  $item ) {
		$edit_link = admin_url( 'post.php?action=edit&post=' .  $item->id  );
		$view_link = get_permalink( $item->id ); 
		$output    = '';

		// Title.
		$output .= '<strong><a href="' . esc_url( $edit_link ) . '" class="row-title">' . esc_html(  $item->id   ) . '</a></strong>';

		// Get actions.
		$actions = array(
			'edit'   => '<a target="_blank" href="' . esc_url( $edit_link ) . '">' . esc_html__( 'Edit', 'my_plugin' ) . '</a>',
			'view'   => '<a target="_blank" href="' . esc_url( $view_link ) . '">' . esc_html__( 'View', 'my_plugin' ) . '</a>',
		);

		$row_actions = array();

		foreach ( $actions as $action => $link ) {
			$row_actions[] = '<span class="' . esc_attr( $action ) . '">' . $link . '</span>';
		}

		$output .= '<div class="row-actions">' . implode( ' | ', $row_actions ) . '</div>';

		return $output;
	}

Which shows in my WP Admin table as:

And that’s it! My table now has a custom row action for the “id” column.

For code examples have a look at:

Leave a Comment

Your email address will not be published. Required fields are marked *