2017-05-04 29 views
0

我已經從上傳文件夾(2017)中刪除了所有圖像,現在我在主頁和文章頁面上獲取了2017年所有帖子的圖像鏈接(刪除圖像)。那麼如何才能從前端刪除所有破碎的圖像?從Wordpress中刪除所有空圖像鏈接

有什麼想法嗎?

enter image description here

enter image description here

+0

您需要創建一個腳本,用於檢查wp-uploads/2017文件夾中是否有圖像。如果找不到圖片,請從該帖子內容中刪除。 –

+0

@Faysal Mahamud,是的,這是真的我需要腳本,我正在尋找是否有人可以幫助我。 –

+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); 
    // } 

} 
+0

感謝您的辛勤工作@Faysal Mahamud,但不幸的是我在functions.php中添加腳本後沒有看到任何更改。另外,它會刪除所有帖子內容的所有圖片,對不對?我們是否可以檢查某些日期範圍,例如從一開始到2015年6月30日(這些帖子中有圖片應該隱藏空幀或精選圖片,因爲我會從上傳的所有圖片中刪除從開始到2015-06-30 )。謝謝 –

+0

這裏有一點點錯誤。我忘記檢查存在於wp-uploads文件夾目錄中的圖像。這就是爲什麼它會刪除帖子內容中的所有圖片。這是一條線路改變。對於您在問題中未提及的精選圖片。奧基,我會用帖子圖片和特色圖片更新我的答案。等幾分鐘。謝謝 –

+0

請在更新代碼後告訴我。 –

相關問題