Take a look at the AJAX documentation, there are plenty of examples on this site and across the Googles to trigger a server event without refreshing the page.
In this case, WP is listening to an AJAX call that looks like http://example.com/wp-admin/admin-ajax.php?action=wpse20160318_batch_update
. When triggered, it’ll run through your batch process an output a JSON message that can be consumed by JavaScript after the call is completed.
The major modifications are just adding an AJAX listener to trigger the batch_update_meta
, removing any echo
s, and returning JSON when complete.
function batch_update_meta() {
$post_type = "listings";
$post_type_object = get_post_type_object( $post_type );
$label = $post_type_object->label;
$processed = array ();
$posts = get_posts( array (
'post_type' => $post_type,
'post_status' => 'publish',
'suppress_filters' => false,
'posts_per_page' => - 1,
) );
foreach ( $posts as $post ) {
$key1 = 'my_meta_key_1';
$key2 = 'my_meta_key_2';
$meta_value1 = get_post_meta( $post->ID, $key1, true );
if ( ! empty( $meta_value1 ) ) {
// Returns a string after it finishes process.
$meta_value2 = media_process( $meta_value1, $post->ID );
// Update the meta
update_post_meta( $post->ID, $key2, $meta_value2, $meta_value1 );
// Add to our success list
$processed[] = $post->post_title;
}
else {
//...
}
}
// give a response for AJAX
wp_send_json_success( array (
'label' => $label,
'processed' => $processed,
'message' => 'Batch Completed.',
) );
}
// callback for AJAX function
function wpse20160318_batch_update_meta() {
// run your batch update
batch_update_meta();
}
// must be logged in to trigger - http://example.com/wp-admin/admin-ajax.php?action=wpse20160318_batch_update
add_action( 'wp_ajax_wpse20160318_batch_update', 'wpse20160318_batch_update_meta' );