WordPress自动将文章标题作为图片alt标签

今天为大家介绍如何自动将文章标题作为图片alt标签。其实很简单,使用下方代码中的其中一个即可,只需将以下代码添加到主题functions.php最后?php>前即可实现。

WordPress自动将文章标题作为图片alt标签

国外大神方法

将下面的代码添加到当前主题函数模板functions.php中:

function callback($buffer) {
/* modify buffer here, and then return the updated code*/
$title='';
$res = preg_match('/<title>(.*?)</title>/', $buffer, $title_matches);
if ($res) {
/*Clean up title: remove EOL's and excessive whitespace.*/
$title = preg_replace('/s+/', ' ', $title_matches[1]);
$title = trim($title);
}
preg_match_all('/<img (.*?)/>/', $buffer, $images);
if(!is_null($images)) {
foreach($images[1] as $index => $value) {
preg_match('/alt="(.*?)"/', $value, $img);
preg_match('/alt='(.*?)'/', $value, $img2);
if(!is_null($images)) {
if((!isset($img[1]) || $img[1] == '') || (!isset($img2[1]) || $img2[1] == '')) {
$new_img = str_replace('<img', '<img alt="'.$title.'"', $images[0][$index]);
$buffer = str_replace($images[0][$index], $new_img, $buffer);
}
}
}
}
return $buffer;
}
function buffer_start() { ob_start(); }
function buffer_end() { echo callback(ob_get_clean()); }
add_action('wp', 'buffer_start', 0);
add_action('wp_footer', 'buffer_end');
//代码源自:https://deano.me/2017/03/wordpress-fill-missingempty-alt-tags-with-title-for-seo//

这段代码中虽然加了缓冲区,但还是会降低效率,建议安装静态缓存插件。

常用方法(推荐)

上方代码运行时会对服务器性能造成可能性的降低,推荐一种常用方法,使用以下代码即可!

//将文章标题作为图片alt标签//
function img_alt($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_bloginfo('name').'" title="'.get_the_title().'-'.get_bloginfo('name').'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
}
}
return $content;
}
add_filter('the_content', 'img_alt', 99999);

代码效果:

WordPress自动将文章标题作为图片alt标签

如果不想带有站点名称,可以使用以下代码:

//将文章标题作为图片alt标签,不带站点名//
function img_alt($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().'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
}
}
return $content;
}
add_filter('the_content', 'img_alt', 99999);

代码效果:

WordPress自动将文章标题作为图片alt标签

如果有安装缓存插件和使用CDN的站长刷新缓存就可以看到效果了。

WordPress教程

WordPress 上传图片自动压缩教程

2021-5-6 0:24:50

WordPress教程

WordPress自动判断百度是否收录函数代码

2021-5-6 18:25:35

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索