[ 'name' => __( 'Activity Log', 'ai-bulk-post' ), 'singular_name' => __( 'Log Entry', 'ai-bulk-post' ), ], 'public' => false, 'show_ui' => false, 'supports' => [], 'map_meta_cap' => true, ] ); } public static function log( int $agent_id, string $level, string $message, int $post_id = 0 ): void { wp_insert_post( [ 'post_type' => self::POST_TYPE, 'post_status' => 'publish', 'post_title' => wp_strip_all_tags( $message ), 'meta_input' => [ 'aibp_log_agent_id' => $agent_id, 'aibp_log_level' => $level, 'aibp_log_post_id' => $post_id, 'aibp_log_time' => gmdate( 'Y-m-d H:i:s' ), ], ] ); } public static function get_logs( int $agent_id = 0, int $limit = 50, int $offset = 0 ): array { $args = [ 'post_type' => self::POST_TYPE, 'posts_per_page' => $limit, 'offset' => $offset, 'orderby' => 'date', 'order' => 'DESC', ]; if ( $agent_id > 0 ) { $args['meta_query'] = [ [ 'key' => 'aibp_log_agent_id', 'value' => $agent_id, 'type' => 'NUMERIC', ], ]; } $query = new \WP_Query( $args ); $results = []; foreach ( $query->posts as $post ) { $results[] = [ 'id' => $post->ID, 'agent_id' => (int) get_post_meta( $post->ID, 'aibp_log_agent_id', true ), 'level' => get_post_meta( $post->ID, 'aibp_log_level', true ), 'message' => $post->post_title, 'post_id' => (int) get_post_meta( $post->ID, 'aibp_log_post_id', true ), 'time' => get_post_meta( $post->ID, 'aibp_log_time', true ), ]; } wp_reset_postdata(); return $results; } public static function delete_old_logs( int $retention_days = 90 ): void { global $wpdb; $cutoff = gmdate( 'Y-m-d H:i:s', strtotime( '-' . $retention_days . ' days' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->posts} WHERE post_type = %s AND post_date < %s", self::POST_TYPE, $cutoff ) ); } }