答案 0 :(得分:0)
在functions.php中添加以下代码
代码经过测试且运行正常。
function get_post_images_from_body(){
// get all post from post type.
$posts = get_posts( array( 'post_type' => 'post') );
$post_images = array();
foreach($posts as $post){
$szSearchPattern = '~<img [^\>]*\ />~';
preg_match_all( $szSearchPattern, $post->post_content, $images );
$iNumberOfPics = count($images[0]);
if ( $iNumberOfPics > 0 ) {
for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
$post_images[$post->ID] = $images[0];
};
}
}
return $post_images;
}
function attachment_id($image_url) {
global $wpdb;
$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $image_url ) );
return $attachment_id;
}
function update_post_content($id,$content){
$my_post = array(
'ID' => $id,
'post_content' => $content,
);
// Update the post into the database
wp_update_post( $my_post );
}
$post_images = get_post_images_from_body();
foreach($post_images as $key => $value){
preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $value[0], $result);
$image_src = array_pop($result);
$file_path = $image_src;
$file_name = basename($image_src);
$post = get_post($key);
$content = preg_replace("/<img[^>]+\>/i", " ", $post->post_content);
update_post_content($key,$content);
//if you want to delete attachment id which is associated with post, comment out the following code.
//
// $id = attachment_id($file_path);
// if(!empty($id)){
// wp_delete_attachment( $id );
// }
}