如何在WordPress中创建删除功能?

时间:2018-06-26 07:23:21

标签: wordpress delete-row

我在wordpress的信息中心中创建了一个删除按钮。我需要添加删除功能以删除仪表板和数据库中的特定行。我的代码如下:

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

Screenshot

1 个答案:

答案 0 :(得分:1)

首先将按钮列更改为此:

<td><a class="button" href="?page=wpdocs-unsub-email-list&deletemail=<?php 
echo $result->mail;?>" 
style="color: red;">DELETE</a></td>

然后将此代码添加到函数的顶部

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"])));
  }
//...

尽管上述步骤可以解决您的任务,但是您可以通过添加反CSRF随机数使其更加安全。

<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>

然后在功能中可以对其进行验证:

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"])));
  }
//....