WordPress上传图片时图片不会自动添加ALT和TITLE,这样非常不利于SEO优化,手动添加又非常免费。织梦无忧分享一段WordPress图片自动添加Alt和title方法。

WordPress图片自动添加Alt和title

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

add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
$my_image_title = get_post( $post_ID )->post_title;
// Sanitize the title:  remove hyphens, underscores & extra spaces:
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $my_image_title );
// Sanitize the title:  capitalize first letter of every word (other letters lower case):
$my_image_title = ucwords( strtolower( $my_image_title ) );
// Create an array with the image meta (Title, Caption, Description) to be updated
// Note:  comment out the Excerpt/Caption or Content/Description lines if not needed
$my_image_meta = array(
'ID'=> $post_ID,// Specify the image (ID) to be updated
'post_title'=> $my_image_title,// Set image Title to sanitized title
'post_excerpt'=> $my_image_title,// Set image Caption (Excerpt) to sanitized title
'post_content'=> $my_image_title,// Set image Description (Content) to sanitized title
);
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
} 
}

代码可以过滤掉图片名称中的空格等多余元素,对之前上传的图片无效。

本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!邮箱:yangbinvap@qq.com分享目的仅供大家学习和交流,您必须在下载后24小时内删除!不得使用于非法商业用途,不得违反国家法律。否则后果自负!本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!如有链接无法下载、失效或广告,请联系管理员处理!本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员! 精力有限,不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别。