WordPress site owners often neglect to add alt attributes to their images when publishing posts, which negatively impacts seo.幸亏,网络上有许多教程教如何自动为文章和图片添加ALT属性。这里提供一个国外的方法,你可以在你的主题功能模板functions.php中加入以下代码:
“`php
function add_alt_attribute($buffer) {
// Modify the buffer and return the updated code
$title = ”;
preg_match(‘/
if (!empty($title_matches)) {
// Clean the title: rEMOve EOL and excess whitespace
$title = preg_replace(‘/\s+/’, ‘ ‘, $title_matches[1]);
$title = trim($title);
preg_match_all(‘//’, $buffer, $images);
if (!empty($images)) {
foreach ($images[1] as $index => $value) {
preg_match(‘/alt=”(.*?)”/’, $value, $img);
preg_match(‘/alt=\'(.*?)\’/’, $value, $img2);
if (empty($img) || empty($img[1]) || empty($img2) || empty($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 start_buffer() {
ob_start();
}
function end_buffer() {
echo apply_filters('add_alt_attribute', ob_get_clean());
}
add_Action('wp_head', 'start_buffer', 0);
add_action('wp_footer', 'end_buffer');
“`
尽管代码中使用了缓冲区,但这可能会略微影响性能。因此,建议安装静态缓存插件以提高效率。
另外一种方法如下:
“`php
function auto_img_alt($content) {
global $post;
preg_match_all('//’, $content, $images);
if (!empty($images)) {
foreach ($images[1] as $index => $value) {
$new_img = str_replace(‘<img ', '<img alt="'.get_the_title().'-'.get_bloginfo('name'), '" src=', '" src=', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
}
}
return $content;
}
add_filter('the_content', 'auto_img_alt', 99999);
“`