从Wordpress中删除所有空图像链接
我已经从上传文件夹(2017)中删除了所有图像,现在我在主页和文章页面上获取了2017年所有帖子的图像链接(删除图像)。那么如何才能从前端删除所有破碎的图像?从Wordpress中删除所有空图像链接
有什么想法吗?
添加以下代码中的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);
// }
}
感谢您的辛勤工作@Faysal Mahamud,但不幸的是我在functions.php中添加脚本后没有看到任何更改。另外,它会删除所有帖子内容的所有图片,对不对?我们是否可以检查某些日期范围,例如从一开始到2015年6月30日(这些帖子中有图片应该隐藏空帧或精选图片,因为我会从上传的所有图片中删除从开始到2015-06-30 )。谢谢 –
这里有一点点错误。我忘记检查存在于wp-uploads文件夹目录中的图像。这就是为什么它会删除帖子内容中的所有图片。这是一条线路改变。对于您在问题中未提及的精选图片。奥基,我会用帖子图片和特色图片更新我的答案。等几分钟。谢谢 –
请在更新代码后告诉我。 –
您需要创建一个脚本,用于检查wp-uploads/2017文件夹中是否有图像。如果找不到图片,请从该帖子内容中删除。 –
@Faysal Mahamud,是的,这是真的我需要脚本,我正在寻找是否有人可以帮助我。 –
好的,等一下。 :) –