{
    分享网正式开通,我们为大家提供免费资源,欢迎大家踊跃投稿!

WordPress图片自动添加Alt和title

WordPress上传图片时图片不会自动添加ALT和TITLE,这样非常不利于SEO优化,手动添加又非常免费。精准像素分享一段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 );
} 
}

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


资源均来自第三方,谨慎下载,前往第三方网站下载


米微资源分享网 , 版权所有丨本站资源仅限于学习研究,严禁从事商业或者非法活动!丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:WordPress图片自动添加Alt和title
喜欢 ()分享 (0)