Delete row of custom table in WordPress using AJAX

Nonce

You are going to want to set a nonce hidden field or to the element so that you can verify the request. Take a look at the codex for examples.

Setting the POST ID and Nonce

You will need to add the id of the specific post to the delete button or to a hidden input field associated with that entry. I have the example setup so you will need to add the post_id and the nonce to the element id in a format such as #delete_postid_nonce. Your element ID would need to end up like so: #delete_12_94f3a1e666.

You could assign it using: $element_id = 'delete_' . $products->post_id . '_' . wp_create_nonce('delete_' . $products->post_id );

Add Actions

These need to be placed in functions.php or in a custom plugin.

You will notice there are two add_action calls. One is for privileged users (i.e. they are logged in) and one is for non-privileged users. Remove one or the other if you don’t need both. You can read more about that on the Codex.

Delete_Row() Function

This need to be placed in functions.php or in a custom plugin.

Here you are grabbing the id that we we sent in the data object of the ajax call. That gets parsed and put in the the POST array since the type of the ajax call is set to POST.

Then you explode() the ID out of the element id sent in the ajax call (e.g. ‘#delete_12_94f3a1e666’) which would leave you with $id = array('delete', 12, '94f3a1e666');. So the post_id is equal to index [1].

Then you echo to return data to the success portion of the ajax call. And then you kill the php function by calling `die’.


You will need to modify this code to make it work 100%.

JS:

jQuery(document).on('click', '.delete', function () {
    var id = this.id;
    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {"action": "your_delete_action", "element_id": id},
        success: function (data) {
            //run stuff on success here.  You can use `data` var in the 
           //return so you could post a message.  
        }
    });
});

PHP:

function delete_row() {
    $id = explode('_', sanitize_text($_POST['element_id']));
    if (wp_verify_nonce($id[2], $id[0] . '_' . $id[1])) {
                $table="yourtable";
        $wpdb->delete( $table, array( 'post_id' => $id[1] ) );

        echo 'Deleted post';
        die;
    } else {
        echo 'Nonce not verified';
        die;
    }

}

add_action('wp_ajax_your_delete_action', 'delete_row');
add_action( 'wp_ajax_nopriv_your_delete_action', 'delete_row');

Leave a Comment