Skip to content

prepare_data()

John P. Bloch edited this page Jul 15, 2014 · 2 revisions

Use this method to prepare the action's data for use in the asynchronous process. Data will be given to prepare_data() as an indexed array, just as it would if you used func_get_args() to get a function's arguments. This method needs to return an array containing the data in a more useful format. Since these values will be sent in a POST request, it's advisable to stick to scalar values for the most part. For example, on 'save_post', the action provides $post_id and the $post object, so we might do this:

protected function prepare_data($data){
	$post_id = $data[0];
	return array( 'post_id' => $post_id );
}

If for any reason the asynchronous task needs to be canceled, you will need to throw an exception:

protected function prepare_data($data){
	$post_id = $data[0];
	$post = $data[1];
	if( 'post' !== $post->post_type ) {
		throw new Exception( 'We only want async tasks for posts' );
	}
	return array( 'post_id' => $post_id );
}

The library will handle catching the exception and will prevent the request from running if it catches an Exception.