WordPress上传图片时图片不会主动增加ALT和TITLE,这样十分不利于SEO优化,手动增加又十分免费。织梦无忧共享一段WordPress图片主动增加Alt和title办法。

将下面的代码增加到当时主题函数模板functions.php中:

add_action('add_attachment','my_set_image_meta_upon_image_upload');
functionmy_set_image_meta_upon_image_upload($post_ID){
//Checkifuploadedfileisanimage,elsedonothing
if(wp_attachment_is_image($post_ID)){
$my_image_title=get_post($post_ID)->post_title;
//Sanitizethetitle:removehyphens,underscores&extraspaces:
$my_image_title=preg_replace('%\s*[-_\s]+\s*%','',$my_image_title);
//Sanitizethetitle:capitalizefirstletterofeveryword(otherletterslowercase):
$my_image_title=ucwords(strtolower($my_image_title));
//Createanarraywiththeimagemeta(Title,Caption,Description)tobeupdated
//Note:commentouttheExcerpt/CaptionorContent/Descriptionlinesifnotneeded
$my_image_meta=array(
'ID'=>$post_ID,//Specifytheimage(ID)tobeupdated
'post_title'=>$my_image_title,//SetimageTitletosanitizedtitle
'post_excerpt'=>$my_image_title,//SetimageCaption(Excerpt)tosanitizedtitle
'post_content'=>$my_image_title,//SetimageDescription(Content)tosanitizedtitle
);
//SettheimageAlt-Text
update_post_meta($post_ID,'_wp_attachment_image_alt',$my_image_title);
//Settheimagemeta(e.g.Title,Excerpt,Content)
wp_update_post($my_image_meta);
}
}

代码能够过滤掉图片称号中的空格等剩余元素,对之前上传的图片无效。

声明:有的资源均来自网络转载,版权归原作者所有,如有侵犯到您的权益 请联系邮箱:123456@qq.com 我们将配合处理!

原文地址:WordPress图片自动添加Alt和title发布于2022-05-19 07:43:31

相关推荐