最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

images - How to generate alt attributes with phpfilters?

programmeradmin3浏览0评论

I would like to generate to generate some kind of automatic alt attributes for the images, if they don't have alt set up.

Found this code, but it doesn't work for some reason:

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

I would like to generate to generate some kind of automatic alt attributes for the images, if they don't have alt set up.

Found this code, but it doesn't work for some reason:

function add_alt_tags($content)
{
    global $post;
    preg_match_all('/<img (.*?)\/>/', $content, $images);
    if(!is_null($images))
    {
        foreach($images[1] as $index => $value)
        {
            if(!preg_match('/alt=/', $value))
            {
                $new_img = str_replace('<img', '<img alt="'.$post->post_title.'"', $images[0][$index]);
                $content = str_replace($images[0][$index], $new_img, $content);
            }
        }
    }
    return $content;
}
add_filter('the_content', 'add_alt_tags', 99999);
Share Improve this question asked Nov 16, 2020 at 8:44 RunnickRunnick 1,0593 gold badges14 silver badges26 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Maybe not the best solution, but did it like this:

function add_alt_tags($content)
{
    global $post;
    $content = str_replace('alt=""', 'alt="'.$post->post_title .'"',
    $content);
    return $content;
}
add_filter('the_content', 'add_alt_tags', 100);

发布评论

评论列表(0)

  1. 暂无评论