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

I love WordPress, WooCommerce and Gutenberg so much. 12 yrs of experience.

Need some custom developer help? Get in touch