I created a delete button in dashboard in wordpress. i need to add delete functionality to delete a specific row in the dashboard and in database also. my code is given below:
add_action('admin_menu', 'wpdocs_unsub_add_pages');
function wpdocs_unsub_add_pages()
{
add_menu_page(__('message', 'textdomain'),
__('Messages', 'textdomain'), 'manage_options',
'wpdocs-unsub-email-list',
'wpdocs_unsub_page_callback', '');
}
function wpdocs_unsub_page_callback()
{
global $wpdb;
$results = $wpdb->get_results("select * from wp_customer_service");
?>
<table border="1">
<tr>
<th>SL</th>
<th>MAIL</th>
<th>SUBJECT</th>
<th>MESSAGE</th>
<th>DATE</th>
<th>ACTION</th>
</tr>
<?php
$i = 1;
foreach ($results as $result) {
// echo '<pre>';
// print_r($result);
// echo '</pre>';
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $result->mail; ?></td>
<td><?php echo $result->subject1; ?></td>
<td><?php echo $result->Message1; ?></td>
<td><?php echo $result->Date; ?></td>
<td><input type="button" value="DELETE" style="color: red;"></td>
</tr>
</table>
<?php
}
}
First change button column to this:
<td><a class="button" href="?page=wpdocs-unsub-email-list&deletemail=<?php
echo $result->mail;?>"
style="color: red;">DELETE</a></td>
Then add this code to the top part of the function
function wpdocs_unsub_page_callback()
{
if (isset($_GET["deletemail"])){
global $wpdb;
$wpdb->query($wpdb->prepare("delete from wp_customer_service
where mail=%s",urldecode($_GET["deletemail"])));
}
//...
Although above steps will solve your task, you can make it more secure with adding anti CSRF nonce.
<td><a class="button" href="<?php
echo wp_nonce_url('?page=wpdocs-unsub-email-list&deletemail='.$result->mail,"del_nonce","del_nonce");?>"
style="color: red;">DELETE</a></td>
Then in function you can validate it:
function wpdocs_unsub_page_callback()
{
if (isset($_GET["deletemail"]) and isset($_GET['del_nonce'])
and wp_verify_nonce($_GET['del_nonce'], 'del_nonce')) {
global $wpdb;
$wpdb->query($wpdb->prepare("delete from wp_customer_service where
mail=%s",urldecode($_GET["deletemail"])));
}
//....