WordPress自动用文章标题为图片添加alt标签

图片[1]-WordPress自动用文章标题为图片添加alt标签-夏末浅笑

对于懂SEO的人都了解,网站alt标签对网站内部优化很重要,尤其是对于搜索引擎。wordpress写文章插入图片会自动生成一个alt标签,但大多数主题都需要发布文章时自己填写alt标签信息。今天为大家介绍的是如何使用文章标题为文章图片自动添加alt标签。其实很简单,只需将以下代码添加到主题functions.php最后?php>前即可实现。

//自动用文章标题为图片添加alt
add_filter('the_content', 'imagesalt');
function imagesalt($content) {
       global $post;
       $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
       $replacement = '<a$1href=$2$3.$4$5 alt="'.$post->post_title.'" title="'.$post->post_title.'"$6>';
       $content = preg_replace($pattern, $replacement, $content);
       return $content;
}

function image_alt_tag($content){
    global $post;preg_match_all('/<img (.*?)\/>/', $content, $images);
    if(!is_null($images)) {foreach($images[1] as $index => $value)
    {
        $new_img = str_replace('<img', '<img alt="'.get_the_title().'-'.get_option('blogname').'"', $images[0][$index]);
        $content = str_replace($images[0][$index], $new_img, $content);}}
    return $content;
}
add_filter('the_content', 'image_alt_tag', 99999);

 

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容