修改WordPress媒体文件的上传时间和路径

知更鸟
知更鸟
站长
2399
文章
0
粉丝
WordPress评论0阅读模式

如果想修改WordPress某个媒体文件的上传时间和路径,并同时更新引用文章中图片的链接,可以尝试使用下面的代码:

修改WordPress媒体文件的上传时间和路径

/**
 * 修改指定ID媒体文件的上传时间和路径
 * 使用方法:update_specific_media_date(123, '2025-04-28 00:00:00');
 *
 * @param int    $attachment_id 附件ID
 * @param string $new_date 新的日期时间,格式:Y-m-d H:i:s
 * @return bool|WP_Error 成功返回true,失败返回WP_Error
 */
function update_specific_media_date( $attachment_id, $new_date ) {
	// 检查是否为媒体文件
	if ( ! wp_attachment_is_image( $attachment_id ) ) {
		return new WP_Error( 'invalid_attachment', '指定的ID不是图片附件' );
	}

	// 更新媒体文件日期
	$update_post = array(
		'ID'            => $attachment_id,
		'post_date'     => $new_date,
		'post_date_gmt' => get_gmt_from_date( $new_date ),
	);

	// 更新数据库中的日期
	$result = wp_update_post( $update_post );

	if ( is_wp_error( $result ) ) {
		return $result;
	}

	// 获取当前媒体文件路径
	$current_file = get_attached_file( $attachment_id );
	$upload_dir   = wp_upload_dir();

	// 生成新的媒体文件路径
	$time       = strtotime( $new_date );
	$new_year   = date( 'Y', $time );
	$new_month  = date( 'm', $time );
	$filename   = basename( $current_file );
	$new_subdir = "$new_year/$new_month";
	$new_file   = $upload_dir['basedir'] . "/$new_subdir/$filename";

	// 获取旧的URL和新的URL
	$old_url = wp_get_attachment_url( $attachment_id );
	$new_url = $upload_dir['baseurl'] . "/$new_subdir/$filename";

	// 创建新目录
	if ( ! file_exists( dirname( $new_file ) ) ) {
		wp_mkdir_p( dirname( $new_file ) );
	}

	// 移动文件到新位置
	if ( file_exists( $current_file ) ) {
		if ( @rename( $current_file, $new_file ) ) {
			// 更新附件元数据
			update_attached_file( $attachment_id, "$new_subdir/$filename" );

			// 更新所有图片尺寸的路径
			$metadata = wp_get_attachment_metadata( $attachment_id );
			if ( is_array( $metadata ) ) {
				$metadata['file'] = "$new_subdir/$filename";
				wp_update_attachment_metadata( $attachment_id, $metadata );
			}

			// 更新所有使用此图片的文章内容
			global $wpdb;
			$posts = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT ID, post_content FROM $wpdb->posts 
                    WHERE post_content LIKE %s 
                    AND post_type NOT IN ('revision', 'attachment')",
					'%' . $wpdb->esc_like( $old_url ) . '%'
				)
			);

			foreach ( $posts as $post ) {
				$updated_content = str_replace( $old_url, $new_url, $post->post_content );
				$update_result   = $wpdb->update(
					$wpdb->posts,
					array( 'post_content' => $updated_content ),
					array( 'ID' => $post->ID )
				);
				if ( $update_result !== false ) {
					clean_post_cache( $post->ID );
				}
			}

			return true;
		}
	}

	return new WP_Error( 'move_failed', '无法移动文件到新位置' );
}

使用方法:

update_specific_media_date( 32, '2024-12-28 00:00:00' );

其中:数字32是媒体ID,后面是时间。

将上述代码添加到当前主题函数模板functions.php中,刷新任意页面,会自动将媒体文件移动到相应的目录,并同时更新引用文章中的图片链接。

本站文章大部分为原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
微信号已复制
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
匿名

发表评论

匿名网友

拖动滑块以完成验证