wp_ajax_get_revision_diffs()
云策文档标注
概述
wp_ajax_get_revision_diffs() 是一个 WordPress AJAX 处理函数,用于获取文章修订版本的差异对比。它通过 AJAX 请求处理用户权限验证、加载修订数据并返回差异信息。
关键要点
- 函数位于 wp-admin/includes/ajax-actions.php,处理 AJAX 请求以获取修订差异。
- 验证用户权限:需要当前用户具有编辑指定文章的权限(edit_post)。
- 加载文章修订:使用 wp_get_post_revisions() 预加载修订数据,并检查是否存在修订。
- 设置脚本超时:通过 set_time_limit() 增加超时时间,确保有足够时间处理差异 UI 设置。
- 处理比较请求:遍历请求中的 compare 参数,解析比较版本(from:to 格式),并调用 wp_get_revision_ui_diff() 获取差异字段。
- 返回 JSON 响应:使用 wp_send_json_success() 或 wp_send_json_error() 返回成功或错误响应。
代码示例
function wp_ajax_get_revision_diffs() {
require ABSPATH . 'wp-admin/includes/revision.php';
$post = get_post( (int) $_REQUEST['post_id'] );
if ( ! $post ) {
wp_send_json_error();
}
if ( ! current_user_can( 'edit_post', $post->ID ) ) {
wp_send_json_error();
}
// Really just pre-loading the cache here.
$revisions = wp_get_post_revisions( $post->ID, array( 'check_enabled' => false ) );
if ( ! $revisions ) {
wp_send_json_error();
}
$return = array();
// Increase the script timeout limit to allow ample time for diff UI setup.
if ( function_exists( 'set_time_limit' ) ) {
set_time_limit( 5 * MINUTE_IN_SECONDS );
}
foreach ( $_REQUEST['compare'] as $compare_key ) {
list( $compare_from, $compare_to ) = explode( ':', $compare_key ); // from:to
$return[] = array(
'id' => $compare_key,
'fields' => wp_get_revision_ui_diff( $post, $compare_from, $compare_to ),
);
}
wp_send_json_success( $return );
}注意事项
- 函数依赖于 wp-admin/includes/revision.php 文件,确保在调用前已包含。
- 权限检查是关键步骤,防止未授权用户访问修订数据。
- compare 参数应为数组,包含以“from:to”格式指定的比较版本键。
- 超时设置(5 * MINUTE_IN_SECONDS)有助于处理大量修订数据时的性能。
原文内容
Handles getting revision diffs via AJAX.
Source
function wp_ajax_get_revision_diffs() {
require ABSPATH . 'wp-admin/includes/revision.php';
$post = get_post( (int) $_REQUEST['post_id'] );
if ( ! $post ) {
wp_send_json_error();
}
if ( ! current_user_can( 'edit_post', $post->ID ) ) {
wp_send_json_error();
}
// Really just pre-loading the cache here.
$revisions = wp_get_post_revisions( $post->ID, array( 'check_enabled' => false ) );
if ( ! $revisions ) {
wp_send_json_error();
}
$return = array();
// Increase the script timeout limit to allow ample time for diff UI setup.
if ( function_exists( 'set_time_limit' ) ) {
set_time_limit( 5 * MINUTE_IN_SECONDS );
}
foreach ( $_REQUEST['compare'] as $compare_key ) {
list( $compare_from, $compare_to ) = explode( ':', $compare_key ); // from:to
$return[] = array(
'id' => $compare_key,
'fields' => wp_get_revision_ui_diff( $post, $compare_from, $compare_to ),
);
}
wp_send_json_success( $return );
}
Changelog
| Version | Description |
|---|---|
| 3.6.0 | Introduced. |