我们在编辑文章插入图片的时候最好给图片设置好alt和title属性,这样有利于图片SEO优化,不过如果图片很多,一个一个的设置就有一些繁琐了,这里告诉大家一个纯代码实现wordpress文章图片自动添加alt和title属性的方法。
将下面代码复制粘贴到你使用主题的functions.php文件中即可(代码参考自Tob主题相关功能代码实现)
//文章图片自动添加alt和title属性 add_filter( 'the_content', 'image_alt_tag'); 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().'" title="'.get_the_title().'-'.get_bloginfo('name').'"', $images[0][$index]); $content = str_replace($images[0][$index], $new_img, $content); } } return $content; }
(提示,使用本功能之后无论你之前是否设置过alt和title属性都将使用文章标题作为图片的alt和title属性。)
未经允许不得转载:六四五笔记 » 纯代码实现wordpress文章图片自动添加alt和title属性