Remove Posts in WordPress Dashboard with AJAX

Here is what we are going to implement:

Remove posts in WordPress admin with ajax

Let’s begin with this JavaScript (jQuery) code:

	$(' .row-actions .trash a').click(function( event ){
		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();
			url: ajaxurl,
			data: {
				'action' : 'moveposttotrash',
				'post_id' : postID,
				'_wpnonce' : nonce

The second step is:

add_action('wp_ajax_moveposttotrash', function(){
	check_ajax_referer( 'trash-post_' . $_POST['post_id'] );
	wp_trash_post( $_POST['post_id'] );

This code can go to your theme functions.php file.

Read also

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X