这应该让您开始:
循环所有帖子并构建链接图像文件数组;交叉检查其中是否有链接到,可能需要对其进行批处理或提高超时时间;内存限制,取决于服务器;您正在处理的帖子数。
$posts = get_posts(
array(
\'posts_per_page\' => -1,
\'post_type\' => array( \'post\', \'page\' ),
)
);
$files = array();
foreach ( $posts as $post ) {
if ( preg_match_all( \'/src=(?:\\\'|")(.+?)(?:\\\'|")/\', $post->post_content, $matches ) ) {
foreach ( $matches[1] as $url ) {
// Replace "wp-content/uploads/" with your upload directory if not default setup
if ( preg_match( \'!wp-content/uploads/(.+)$!\', $url, $matches_2 ) )
$files[] = $matches_2[1];
}
}
}
$posts = get_posts(
array(
\'posts_per_page\' => -1,
\'post_mime_type\' => \'image\',
\'post_type\' => \'attachment\',
\'fields\' => \'ids\',
)
);
update_postmeta_cache( $posts );
foreach ( $posts as $post_id ) {
if ( is_file( $file = get_attached_file( $post_id ) ) ) {
if ( $meta = wp_get_attachment_metadata( $post_id ) ) {
$path = dirname( $file );
if ( preg_match( \'!^[0-9]{4}/[0-9]{2}/!\', $meta[\'file\'], $matches ) ) {
// Split date folders with filename for when searching size variations
$suffix = $matches[0];
} else {
$suffix = \'\';
}
if ( ! in_array( $meta[\'file\'], $files ) ) {
// Original file not in post content
// unlink( $file );
}
foreach ( $meta[\'sizes\'] as $name => $data ) {
if ( ! in_array( $suffix . $data[\'file\'], $files ) ) {
// Image size not in post content
// unlink( "$path/{$data[\'file\']}" );
}
}
}
} else {
wp_delete_post( $post_id, true ); // Might as well clean up
}
}
你该怎么处理这件事取决于你自己。如果要保留原始但删除大小变化,请确保将其从中的数据库条目中删除
$meta[\'sizes\']
并使用保存
wp_update_attachment_metadata( $post_id, $meta )
.
您甚至可以使用wp_get_image_editor()
&;更新旧版本src
\'在您的帖子内容中动态显示。