看看AJAX 在文档中,这个网站和谷歌上都有很多例子可以在不刷新页面的情况下触发服务器事件。
在本例中,WP正在侦听一个AJAX调用,该调用如下所示http://example.com/wp-admin/admin-ajax.php?action=wpse20160318_batch_update
. 当被触发时,它将在批处理过程中运行,并输出一条JSON消息,该消息可在调用完成后由JavaScript使用。
主要的修改只是添加一个AJAX侦听器来触发batch_update_meta
, 删除任何echo
s、 完成后返回JSON。
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\' );