From my custom table ($table = $wpdb->prefix . 'user_req';
) I’m showing data with $wpdb->get_results()
and a foreach loop:
I managed to update the database with the individual values from the form where there is a “Submit” button. But, from this table I want to delete any of the row by clicking on the (x)
button on the right of each row. I can use $_GET[]
and can easily delete the row, but in this case I want to use AJAX.
The (x)
button on the right of each of the row is actually:
<input type="button" class="delete" title="Exclude This One"/>
I’m not a code-background, so I’m actually struggling with it. Most of the solution comes when I search, are for raw PHP-mySQL, but I’m trying to deal it with a WordPress way. I could prepare my $wpdb delete query:
<?php $wpdb->delete( $table, array( 'post_id' => $products->post_id ) ); ?>
But couldn’t manage to go with it in an WordPress-AJAX way. Therefore, any help would be greatly appreciated.
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 thenonce
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 thedata
object of the ajax call. That gets parsed and put in the thePOST
array since thetype
of the ajax call is set toPOST
.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 returndata
to thesuccess
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:
PHP: