Remove Posts in WordPress Dashboard with AJAX
Here is what we are going to implement:

Let’s begin with this JavaScript (jQuery) code:
jQuery(function($){ $('body.post-type-post .row-actions .trash a').click(function( event ){ event.preventDefault(); var url = new URL( $(this).attr('href') ), nonce = url.searchParams.get('_wpnonce'), // MUST for security checks row = $(this).closest('tr'), postID = url.searchParams.get('post'), postTitle = row.find('.row-title').text(); row.css('background-color','#ffafaf').fadeOut(300, function(){ row.removeAttr('style').html('<td colspan="5">Post <strong>' + postTitle + '</strong> moved to the Trash.</td>').show(); }); $.ajax({ method:'POST', url: ajaxurl, data: { 'action' : 'moveposttotrash', 'post_id' : postID, '_wpnonce' : nonce } }); }); });
- In case you do not know how to add this JavaScript code, I highly recommend to check this tutorial.
- On line 2 replace
.post-type-post
with a name of a post type you would like to use this code for,.post-type-{POST TYPE NAME}
. - On lines 6,7,9 I use URL API which doesn’t work in older browsers, for me it is OK because I use Chrome. You can check your browser compatibility here.
- You can see on line 7 also, that I exctracted
_wpnonce
parameter from URL string, it is a great idea, because the nonce check is a must for our ajax processing function and we do not have to create it one more time. - The code doesn’t refresh the counts (All, Published, Drafts…)
The second step is:
add_action('wp_ajax_moveposttotrash', function(){ check_ajax_referer( 'trash-post_' . $_POST['post_id'] ); wp_trash_post( $_POST['post_id'] ); die(); });
This code can go to your theme functions.php
file.
- I decided to use anonymous function here, which are supported since PHP 5.3.
- You should remember that
wp_ajax_moveposttotrash
action iswp_ajax_{ACTION}
, whereaction
is the parameter from the previous code sample and you can find it on line 21, also note that we do not usewp_ajax_nopriv_
here because this functionality is going to be used by authorized admins only. - You can also notice that I didn’t pass
$_POST['post_id']
to theintval()
function because here is no needs to do it,get_post()
function which is insidewp_trash_post()
does it instead.