Categories
Advanced

Asynchronous Actions in WordPress Table

In a previous post we added a “Select All” button to the Woocommerce product table. In this tutorial, we will create an asynchronous action that retrieves all of the table product Ids without refreshing the page.

Initially, define our action:

add_action( 'bulk_actions-edit-product', function($bulk_actions){
	$bulk_actions['my-action'] = __( 'Asynchornously get ids', 'my-action');
	return $bulk_actions;	
});

Now we have this option in the products table:

Now we will add the following Javascript:

add_action('current_screen', function($screen){
	if($screen->id == "edit-product"){
			?>
	<script>
	     document.addEventListener("DOMContentLoaded", function() {
                     jQuery("#posts-filter").on("submit", function(ev){
	             var action1 = jQuery("[name=action]").val();
		     if(action1!="my-action") return;
                     ev.preventDefault();

        //this is where we serialize the form
	
                     var unindexed_array =jQuery("#posts-filter").serializeArray();
		     var indexed_array = {};

		     jQuery.map(unindexed_array, function(n, i){
			   indexed_array[n['name']] = n['value'];
		     });

		     jQuery.ajax({
			    url: "admin-ajax.php",
			    type: 'GET',
			    dataType: 'json', // added data type
			    data: indexed_array,
			    success: function(res) {
					console.log(res);
			    },
			    error: function(res){
				    console.log(res)
			    }
		     });
             })
	});
	</script>
	     <?php
	}
});

You can see that we are listening to the form submit event, and checking the value of the action field (don’t forget there is also the action2 field which you may also want to implement). We then check if the action value matches my-action and if so we serialize the form and submit it with an ajax GET request.

In order for the server to handle this we will add the following action:
add_action("wp_ajax_my-action", function(){
	global $wp_query;
	
        add_filter("edit_posts_per_page", function($ppp){
		return -1;
	});
	
	wp_edit_posts_query();
	$posts = $wp_query->posts;
	$ret = [];
	foreach($posts as $post){
		$ret[] = $post->ID;
	}
	wp_send_json($ret);
});

You can notice two things. Firstly, we use the filter edit_posts_per_page to make sure we get all of the ids. Second we call wp_edit_posts_query() and get the results with $wp_query->posts.

Now that we have all of the Ids, we can do whatever we like (probably more asynchronous actions). But for now, we just log them to the console.

Leave a Reply

Your email address will not be published. Required fields are marked *