如何在WordPress中实现自定义表记录文章/页面增删改操作
WordPress 自定义表记录文章/页面操作日志实现方案
一、创建自定义操作日志表
通过插件激活钩子创建符合需求的自定义表,确保表结构与WordPress数据库规范兼容:
// 插件激活时创建自定义操作日志表 register_activation_hook( __FILE__, 'create_operation_log_table' ); function create_operation_log_table() { global $wpdb; $table_name = $wpdb->prefix . 'operation_logs'; // 复用WordPress默认表前缀 $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, user_id bigint(20) NOT NULL, operation_type varchar(20) NOT NULL, table_name varchar(50) NOT NULL, row_id bigint(20) NOT NULL, operation_at datetime NOT NULL, created_at datetime NOT NULL, updated_at datetime NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); }
二、封装日志记录函数
编写通用函数处理日志插入逻辑,统一管理数据格式:
function log_post_operation( $operation_type, $post_id, $user_id ) { global $wpdb; $table_name = $wpdb->prefix . 'operation_logs'; $current_time = current_time( 'mysql' ); // 使用WordPress标准时间格式 $wpdb->insert( $table_name, array( 'user_id' => $user_id, 'operation_type' => $operation_type, 'table_name' => 'wp_posts', // 目标表为WordPress默认文章/页面表 'row_id' => $post_id, 'operation_at' => $current_time, 'created_at' => $current_time, 'updated_at' => $current_time ), array( '%d', '%s', '%s', '%d', '%s', '%s', '%s' ) // 对应字段数据类型 ); }
三、绑定WordPress操作钩子
通过内置钩子监听文章/页面的增删改操作,触发日志记录:
// 监听文章/页面的创建与更新 add_action( 'save_post', 'handle_post_save_log', 10, 3 ); function handle_post_save_log( $post_id, $post, $update ) { // 跳过自动保存、修订版本及非公开内容 if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) || $post->post_status !== 'publish' ) { return; } $operation_type = $update ? 'update' : 'add'; $user_id = $post->post_author; // 获取当前内容的作者ID log_post_operation( $operation_type, $post_id, $user_id ); } // 监听文章/页面的删除操作 add_action( 'before_delete_post', 'handle_post_delete_log' ); function handle_post_delete_log( $post_id ) { $post = get_post( $post_id ); if ( !$post ) return; $user_id = $post->post_author; log_post_operation( 'delete', $post_id, $user_id ); }
额外说明
- 代码建议放在自定义插件文件中,避免主题更新导致代码丢失
- 若需要区分文章和页面,可在
table_name字段存储post或page标识,或保持wp_posts不变,通过row_id结合内容类型判断 - 如需仅记录管理员操作,可在日志函数开头添加判断:
if ( !current_user_can( 'manage_options' ) ) return;
内容的提问来源于stack exchange,提问作者zakir Hossen
相关产品推荐
相关产品推荐

