• 首页
  • 邻居
  • 关于
  • 归档
  • 搜索
  • 夜间模式
    ©2020-2026  我的学习笔记 Theme by OneBlog

    我的学习笔记博客

    搜索
    标签
    # 随笔 # Java # 教程 # openwrt # Mysql # SQL # 爬虫 # post # Js调优 # MAVEN
  • 首页>
  • 教程>
  • 正文
  • WordPress图片的SEO自动加上 title 和 alt 标签

    2025年03月13日 689 阅读 0 评论 988 字

    网站 seo 要求每张图片都要有 alt 属性,手动去改显然不显示,因此写了个函数,将下面的代码加入到主题的 functions.php 文件中即可。

    
    //图片img标签添加alt,title属性
    function imagesalt($content) {
           global $post;
           $pattern ="/<img(.*?)src=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
           $replacement = '<img$1src=$2$3.$4$5 alt="'.$post->post_title.'" title="'.$post->post_title.'"$6>';
           $content = preg_replace($pattern, $replacement, $content);
           return $content;
    }
    add_filter('the_content', 'imagesalt');
    //图片A标签添加alt,title属性
    function aimagesalt($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;
    }
    add_filter('the_content', 'aimagesalt');
    
    
    本文著作权归作者 [ admin ] 享有,未经作者书面授权,禁止转载,封面图片来源于 [ 互联网 ] ,本文仅供个人学习、研究和欣赏使用。如有异议,请联系博主及时处理。
    取消回复

    发表留言
    回复

    首页邻居关于归档
    Copyright©2020-2026  All Rights Reserved.  Load:0.016 s
    京ICP备18019712号
    Theme by OneBlog V3.6.5
    夜间模式

    开源不易,请尊重作者版权,保留基本的版权信息。