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:

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

	});
});

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.

Read also

Misha Rudrastyh

Misha Rudrastyh

I develop websites since 2008, so it is total of 13 years of experience, oh my gosh. Most of all I love love love to create websites with WordPress and Gutenberg, some ideas and thoughts I share throughout my blog.

Need some developer help? Contact me