$max ) { return new WP_Error( 'lao_ud_range_too_large', sprintf( /* translators: %d: maximum allowed ID span */ __( 'ID 区间过大(超过 %d),请缩小范围或改用其他筛选方式。', 'laoupdatedate' ), $max ) ); } } $has_full_range = ! empty( $params['id_range_start'] ) && ! empty( $params['id_range_end'] ); $has_specific = false; if ( ! empty( $params['specific_ids'] ) ) { $ids = self::parse_id_list( $params['specific_ids'] ); $has_specific = ! empty( $ids ); } $has_category = false; if ( ! empty( $params['category_ids'] ) ) { $cat_ids = self::parse_id_list( $params['category_ids'] ); $has_category = ! empty( $cat_ids ); } $has_date = ! empty( $params['date_from'] ) || ! empty( $params['date_to'] ); if ( ! $has_full_range && ! $has_specific && ! $has_category && ! $has_date ) { return new WP_Error( 'lao_ud_no_filters', __( '请至少填写一项有效的筛选条件。', 'laoupdatedate' ) ); } return true; } /** * 校验时间分散参数 * * @param array $spread spread_mode、spread_step_minutes、spread_random_min、spread_random_max * @return true|\WP_Error */ public static function validate_spread_params( $spread ) { if ( ! is_array( $spread ) ) { return new WP_Error( 'lao_ud_spread_invalid', __( '时间分散参数无效。', 'laoupdatedate' ) ); } $mode = isset( $spread['spread_mode'] ) ? sanitize_key( $spread['spread_mode'] ) : 'none'; if ( ! in_array( $mode, array( 'none', 'increment', 'random' ), true ) ) { return new WP_Error( 'lao_ud_spread_mode', __( '时间分散模式无效。', 'laoupdatedate' ) ); } if ( 'increment' === $mode ) { $step = isset( $spread['spread_step_minutes'] ) ? absint( $spread['spread_step_minutes'] ) : 0; if ( $step < 1 ) { return new WP_Error( 'lao_ud_spread_step', __( '递增分散时,间隔分钟须为大于等于 1 的整数。', 'laoupdatedate' ) ); } } if ( 'random' === $mode ) { $min = isset( $spread['spread_random_min'] ) ? (int) $spread['spread_random_min'] : 0; $max = isset( $spread['spread_random_max'] ) ? (int) $spread['spread_random_max'] : 0; if ( $min > $max ) { return new WP_Error( 'lao_ud_spread_random_order', __( '随机分散时,最小偏移须小于或等于最大偏移。', 'laoupdatedate' ) ); } $limit = (int) apply_filters( 'lao_ud_spread_random_limit_minutes', 10080 ); if ( $limit < 1 ) { $limit = 10080; } if ( abs( $min ) > $limit || abs( $max ) > $limit ) { return new WP_Error( 'lao_ud_spread_random_limit', sprintf( /* translators: %d: max absolute offset in minutes */ __( '随机偏移绝对值过大(单端超过 %d 分钟),请缩小范围。', 'laoupdatedate' ), $limit ) ); } } return true; } /** * 根据筛选条件获取文章 ID 列表(兼容旧调用:一次取全量)。 * * @param array $params 筛选参数 * @return array 文章 ID 数组 */ public static function get_post_ids( $params ) { $batch_size = (int) apply_filters( 'lao_ud_query_page_size', 500 ); if ( $batch_size < 1 ) { $batch_size = 500; } $all = array(); $offset = 0; do { $page = self::get_post_ids_page( $params, $offset, $batch_size, false ); if ( empty( $page['ids'] ) ) { break; } $all = array_merge( $all, $page['ids'] ); $offset += $batch_size; } while ( count( $page['ids'] ) === $batch_size ); return array_values( array_unique( array_map( 'absint', $all ) ) ); } /** * 分页获取匹配的文章 ID。 * * @param array $params 筛选参数 * @param int $offset 偏移 * @param int $per_page 每页数量 * @param bool $need_total 是否计算总数 * @return array{ids:int[],total:int|null} */ public static function get_post_ids_page( $params, $offset = 0, $per_page = 50, $need_total = false ) { $empty = array( 'ids' => array(), 'total' => $need_total ? 0 : null, ); $validated = self::validate_filter_params( $params ); if ( is_wp_error( $validated ) ) { return $empty; } $offset = max( 0, (int) $offset ); $per_page = max( 1, (int) $per_page ); $built = self::build_query_args( $params, $per_page, $offset, $need_total ); if ( is_wp_error( $built ) ) { return $empty; } $args = $built['args']; if ( ! empty( $built['id_between'] ) ) { self::$id_between = $built['id_between']; add_filter( 'posts_where', array( __CLASS__, 'filter_posts_where_id_between' ) ); } $query = new WP_Query( $args ); $ids = $query->posts ? $query->posts : array(); if ( ! empty( $built['id_between'] ) ) { remove_filter( 'posts_where', array( __CLASS__, 'filter_posts_where_id_between' ) ); self::$id_between = null; } wp_reset_postdata(); return array( 'ids' => array_values( array_unique( array_map( 'absint', $ids ) ) ), 'total' => $need_total ? (int) $query->found_posts : null, ); } /** * posts_where:按 ID 区间过滤。 * * @param string $where SQL WHERE。 * @return string */ public static function filter_posts_where_id_between( $where ) { if ( empty( self::$id_between ) || ! is_array( self::$id_between ) ) { return $where; } global $wpdb; $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID BETWEEN %d AND %d ", (int) self::$id_between['min'], (int) self::$id_between['max'] ); return $where; } /** * 批量更新文章发布日期 * * @param array $post_ids 文章 ID 数组(可为当前批次) * @param string $new_date 新日期时间 (Y-m-d H:i:s 或 'current') * @param array|bool $args 选项数组;若为 bool 则视为 dry_run(兼容旧调用) * @return array */ public static function update_post_dates( $post_ids, $new_date, $args = array() ) { if ( is_bool( $args ) ) { $args = array( 'dry_run' => $args ); } if ( ! is_array( $args ) ) { $args = array(); } $args = wp_parse_args( $args, array( 'dry_run' => false, 'spread_mode' => 'none', 'spread_step_minutes' => 15, 'spread_random_min' => -60, 'spread_random_max' => 60, 'list_offset' => 0, 'anchor_datetime' => '', 'is_complete' => true, 'total' => null, ) ); $dry_run = ! empty( $args['dry_run'] ); $spread_mode = sanitize_key( $args['spread_mode'] ); if ( ! in_array( $spread_mode, array( 'none', 'increment', 'random' ), true ) ) { $spread_mode = 'none'; } $list_offset = max( 0, (int) $args['list_offset'] ); $max_errors = (int) apply_filters( 'lao_ud_max_errors', 20 ); if ( $max_errors < 1 ) { $max_errors = 20; } $result = array( 'updated' => 0, 'failed' => 0, 'errors' => array(), 'errors_truncated' => 0, 'dry_run' => (bool) $dry_run, 'total' => null !== $args['total'] ? (int) $args['total'] : count( $post_ids ), 'batches' => 1, 'spread_mode' => $spread_mode, 'anchor_datetime' => '', 'processed_in_batch' => 0, ); if ( empty( $post_ids ) ) { $result['errors'][] = __( '未找到符合条件的文章。', 'laoupdatedate' ); return self::finalize_errors( $result, $max_errors ); } $use_current = ( 'current' === $new_date || '' === $new_date ); $new_date_formatted = ''; if ( ! $use_current ) { $new_date_formatted = self::normalize_input_datetime( $new_date ); if ( '' === $new_date_formatted ) { $result['errors'][] = sprintf( /* translators: %s: invalid date input */ __( '无效的日期格式: %s', 'laoupdatedate' ), $new_date ); return self::finalize_errors( $result, $max_errors ); } } $anchor_for_spread = ''; if ( ! empty( $args['anchor_datetime'] ) && is_string( $args['anchor_datetime'] ) ) { $anchor_for_spread = self::normalize_input_datetime( $args['anchor_datetime'] ); } $ordinal = 0; $post_type = apply_filters( 'lao_ud_post_type', 'post' ); foreach ( $post_ids as $post_id ) { $post_id = absint( $post_id ); $list_index = $list_offset + $ordinal; $post = get_post( $post_id ); if ( ! $post || $post->post_type !== $post_type ) { $result['failed']++; self::push_error( $result, $max_errors, sprintf( /* translators: %d: post ID */ __( '文章 ID %d 不存在或非文章类型。', 'laoupdatedate' ), $post_id ) ); $ordinal++; continue; } if ( ! current_user_can( 'edit_post', $post_id ) ) { $result['failed']++; self::push_error( $result, $max_errors, sprintf( /* translators: %d: post ID */ __( '无权限编辑文章 ID %d。', 'laoupdatedate' ), $post_id ) ); $ordinal++; continue; } if ( 'none' !== $spread_mode && $use_current && '' === $anchor_for_spread ) { $anchor_for_spread = current_time( 'mysql' ); } if ( 'none' === $spread_mode ) { $base = $use_current ? current_time( 'mysql' ) : $new_date_formatted; } else { $base = $use_current ? $anchor_for_spread : $new_date_formatted; } $spread_slot = ( 'increment' === $spread_mode ) ? $list_index : $ordinal; $date_to_use = self::apply_spread_to_datetime( $base, $spread_mode, $spread_slot, $post_id, (int) $args['spread_step_minutes'], (int) $args['spread_random_min'], (int) $args['spread_random_max'] ); /** * 在写入数据库前允许按篇调整最终发布时间。 * * @param string $date_to_use 当前计算的 Y-m-d H:i:s * @param int $post_id 文章 ID * @param \WP_Post $post 文章对象 * @param array $context 上下文 */ $date_to_use = apply_filters( 'lao_ud_date_for_post', $date_to_use, $post_id, $post, array( 'new_date' => $new_date, 'dry_run' => $dry_run, 'ordinal' => $ordinal, 'list_index' => $list_index, 'spread_mode' => $spread_mode, ) ); if ( $dry_run ) { $result['updated']++; $ordinal++; continue; } $updated = wp_update_post( array( 'ID' => $post_id, 'post_date' => $date_to_use, 'post_date_gmt' => get_gmt_from_date( $date_to_use ), ), true ); if ( is_wp_error( $updated ) ) { $result['failed']++; self::push_error( $result, $max_errors, sprintf( /* translators: 1: post ID, 2: error message */ __( '文章 ID %1$d 更新失败: %2$s', 'laoupdatedate' ), $post_id, $updated->get_error_message() ) ); } else { $result['updated']++; } $ordinal++; } $result['processed_in_batch'] = $ordinal; $result['anchor_datetime'] = $anchor_for_spread; $result = self::finalize_errors( $result, $max_errors ); if ( ! empty( $args['is_complete'] ) ) { /** * 批量更新发布日期完成后触发。 * * @param array $post_ids 本批次(或全量)文章 ID * @param string $new_date 日期参数 * @param array $result 结果(分批时可能仅含本批次计数,完整累计见管理端日志) */ do_action( 'lao_ud_after_update_dates', $post_ids, $new_date, $result ); } return $result; } /** * 解析逗号分隔的 ID 列表。 * * @param string $raw 原始字符串。 * @return int[] */ private static function parse_id_list( $raw ) { if ( ! is_string( $raw ) || '' === $raw ) { return array(); } $ids = array_map( 'absint', array_filter( array_map( 'trim', explode( ',', $raw ) ) ) ); return array_values( array_filter( $ids ) ); } /** * 构建 WP_Query 参数。 * * @param array $params 筛选参数。 * @param int $per_page 每页。 * @param int $offset 偏移。 * @param bool $need_total 是否需要总数。 * @return array{args:array,id_between:?array}|\WP_Error */ private static function build_query_args( $params, $per_page, $offset, $need_total ) { $post_type = apply_filters( 'lao_ud_post_type', 'post' ); $args = array( 'post_type' => $post_type, 'post_status' => array( 'publish', 'draft', 'pending', 'private' ), 'posts_per_page' => $per_page, 'offset' => $offset, 'fields' => 'ids', 'orderby' => 'ID', 'order' => 'ASC', 'no_found_rows' => ! $need_total, 'cache_results' => false, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ); $id_between = null; $has_range = ! empty( $params['id_range_start'] ) && ! empty( $params['id_range_end'] ); $range_min = 0; $range_max = 0; if ( $has_range ) { $start = absint( $params['id_range_start'] ); $end = absint( $params['id_range_end'] ); $range_min = min( $start, $end ); $range_max = max( $start, $end ); } $specific_ids = array(); if ( ! empty( $params['specific_ids'] ) ) { $specific_ids = self::parse_id_list( $params['specific_ids'] ); if ( $has_range && ! empty( $specific_ids ) ) { $specific_ids = array_values( array_filter( $specific_ids, function ( $id ) use ( $range_min, $range_max ) { return $id >= $range_min && $id <= $range_max; } ) ); if ( empty( $specific_ids ) ) { return new WP_Error( 'lao_ud_empty_intersect', __( '筛选条件无交集。', 'laoupdatedate' ) ); } } } if ( ! empty( $specific_ids ) ) { $args['post__in'] = $specific_ids; } elseif ( $has_range ) { $id_between = array( 'min' => $range_min, 'max' => $range_max, ); } if ( ! empty( $params['category_ids'] ) ) { $cat_ids = self::parse_id_list( $params['category_ids'] ); if ( ! empty( $cat_ids ) ) { // Use category__in instead of tax_query to avoid a slow-query warning for the built-in category taxonomy. $args['category__in'] = $cat_ids; } } if ( ! empty( $params['date_from'] ) || ! empty( $params['date_to'] ) ) { $date_query = array( 'inclusive' => true ); if ( ! empty( $params['date_from'] ) ) { $date_query['after'] = sanitize_text_field( $params['date_from'] ); } if ( ! empty( $params['date_to'] ) ) { $date_query['before'] = sanitize_text_field( $params['date_to'] ); } if ( count( $date_query ) > 1 ) { $args['date_query'] = array( $date_query ); } } return array( 'args' => $args, 'id_between' => $id_between, ); } /** * 追加错误信息(超出上限仅计数)。 * * @param array $result 结果引用。 * @param int $max_errors 上限。 * @param string $message 错误文案。 */ private static function push_error( &$result, $max_errors, $message ) { if ( count( $result['errors'] ) < $max_errors ) { $result['errors'][] = $message; } else { $result['errors_truncated']++; } } /** * 规范化错误字段。 * * @param array $result 结果。 * @param int $max_errors 上限(保留参数供过滤器语义一致)。 * @return array */ private static function finalize_errors( $result, $max_errors ) { unset( $max_errors ); if ( ! isset( $result['errors_truncated'] ) ) { $result['errors_truncated'] = 0; } return $result; } /** * 在基准时间上应用「时间分散」规则。 * * @param string $base_mysql Y-m-d H:i:s * @param string $mode none|increment|random * @param int $ordinal 递增模式下标或随机模式下临时序号 * @param int $post_id 文章 ID * @param int $step 递增间隔(分钟) * @param int $rmin 随机最小偏移(分钟) * @param int $rmax 随机最大偏移(分钟) * @return string */ private static function apply_spread_to_datetime( $base_mysql, $mode, $ordinal, $post_id, $step, $rmin, $rmax ) { if ( 'none' === $mode || ! is_string( $base_mysql ) || '' === $base_mysql ) { return $base_mysql; } try { $timezone = wp_timezone(); $dt = DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', $base_mysql, $timezone ); if ( ! $dt ) { return $base_mysql; } if ( 'increment' === $mode ) { $step = max( 1, absint( $step ) ); return $dt->modify( '+' . ( (int) $ordinal * $step ) . ' minutes' )->format( 'Y-m-d H:i:s' ); } if ( 'random' === $mode ) { if ( $rmin > $rmax ) { $tmp = $rmin; $rmin = $rmax; $rmax = $tmp; } $range = (int) $rmax - (int) $rmin + 1; if ( $range < 1 ) { return $base_mysql; } $h = (int) crc32( 'lao_ud_spread|' . (string) (int) $post_id ); $idx = $h % $range; if ( $idx < 0 ) { $idx += $range; } $offset = (int) $rmin + $idx; return $dt->modify( $offset . ' minutes' )->format( 'Y-m-d H:i:s' ); } } catch ( Exception $e ) { return $base_mysql; } return $base_mysql; } /** * 将输入日期标准化为站点时区下的 mysql datetime。 * * @param string $input 日期字符串 * @return string */ private static function normalize_input_datetime( $input ) { if ( ! is_string( $input ) || '' === $input ) { return ''; } try { $timezone = wp_timezone(); $date = new DateTimeImmutable( $input, $timezone ); return $date->format( 'Y-m-d H:i:s' ); } catch ( Exception $e ) { return ''; } } }