Remove Posts in WordPress Dashboard with AJAX

If you ever tried to remove WordPress comments in admin dashboard, you know that comments are moved to trash asynchronously. In this tutorial I will show how to do the same for custom post types.

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. 11 yrs of experience.

Need some custom developer help? Let me know

Follow Misha

Need some help with WordPress?

If you need some professional developer help, I will be happy to assist you.

Contact me Who I am?

Leave a comment

php js HTML CSS Code

I will only use your personal information to contact you. Privacy Policy