//books submenu
add_submenu_page('lg-pods', 'Books', 'Books', 'manage_options', 'lg-books', 'display_books_page');
/**
* Defines books page = management and edit
*/
function display_books_page() {
$object = pods('books');
//for this pod type we will also use all available fields
$fields = array();
foreach($object->fields as $field => $data) {
$fields[$field] = array('label' => $data['label']);
}
//adding few basic parameters
$object->ui = array(
'item' => 'book',
'items' => 'books',
'fields' => array(
'add' => $fields,
'edit' => $fields,
'duplicate' => $fields,
'manage' => $fields
),
'actions_bulk' => array(
//adds custom function for our own bulk action - empty books' stock
'zero-me' => array(
'label' => 'Empty stock',
'callback' => 'empty_stock'
),
//adds built in delete function
'delete' => array(
'label' => 'Delete',
),
),
);
pods_ui($object);
}
/**
* Bulk action function - empties stock for all books selected by user
*/
function empty_stock($obj) {
//checks if parameter exists
//if yes - it means that we successfully updated data entries and we can display message to the user
//if no - it means that we are running function for the first time
if ( ! isset( $_GET['updated_bulk'] )) {
//$obj->bulk contains all IDs selected by user
$ids = $obj->bulk;
//if we successfully change our items we need to redirect user afterwards
//false by default
$success = false;
//lets count how many items were affected by our function
$items_affected = 0;
if(!empty( $ids )) {
foreach( $ids as $pod_id ) {
//sanitizing ID
$pod_id = pods_absint( $pod_id );
//if the ID is empty - jump out of the current loop iteration
if(empty($pod_id)) {
continue;
}
//getting our pod data entry
$book_pod = pods( 'mytable', $pod_id );
//setting the stock to desired number
$book_pod->save( 'stock', 0 );
//we have successfully changed item ( so we need to redirect later )
$success = true;
//increase the number of updated items
$items_affected++;
}
}
//checking if our bulk action completed successfully
if ( $success ) {
//if yes - redirect our user to manage page
//this redirect us again to our bulk action handler
pods_redirect( pods_var_update( array( 'action_bulk' => 'zero-me', 'updated_bulk' => $items_affected ), array( 'page', 'lang', 'action', 'id' ) ) );
} else {
//otherwise display an error
$obj->error( __( "<strong>Error:</strong> Cannot update stock.", 'localization-domain' ) );
}
} else { //if our get parameter was set we can display 'success' message
$obj->message( __( "<strong>Success!</strong> We have successfully updated stock numbers for <strong>". $_GET['updated_bulk'] ."</strong> entry(-es).", 'localization-domain' ) );
unset( $_GET[ 'updated_bulk' ] );
}
//clean up
$obj->action_bulk = false;
unset( $_GET[ 'action_bulk' ] );
//show manage screen
$obj->manage();
}
|