公告:123目录网为广大站长提供免费收录网站服务,我们将免费进行到底,如需快审服务(10元/站)请联系站长QQ,可自助充值发布。

点击这里在线咨询客服
新站提交
  • 网站:315
  • 待审:0
  • 小程序:12
  • 文章:35791
  • 会员:69

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

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

标签:WordPress图片自动添加Alt和title

下一篇:【帝国cms代码】帝国CMS灵动标签调用标题图片没有图片时显示默认图片

上一篇:【帝国cms代码】帝国CMS发布文章时,同时发布到以下栏目: 采用索引链链方式,怎样避免重复文章调用?

相关文章

  575

注册时间:

网站:1 个   小程序:3 个  文章:12 篇

  • 315

    网站

  • 12

    小程序

  • 35791

    文章

  • 69

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定