Home > Software engineering >  How I can add alt attribute to posted images that are separated from text?
How I can add alt attribute to posted images that are separated from text?

Time:01-16

This is my code to give alt attribute to all images on published post. It works fine for all images on normal post.

function auto_alt_set($html)
{
    global $post;
    $pic_alt = get_the_title();
    if ($pic_alt !== '') {
        $html = str_replace('alt=""', 'alt="' . esc_attr($pic_alt) . '"', $html);
    }
    return $html;
}
add_filter('the_content', 'auto_alt_set');

Now I like to know how I can set alt attribute to images that are extracted from content by the following code.

<?php
$beforeEachImage = "<div>";
$afterEachImage = "</div>";
preg_match_all("/(<img [^>]*>)/", get_the_content(), $matches, PREG_PATTERN_ORDER);
for ($i = 0; isset($matches[1]) && $i < count($matches[1]); $i  ) {
    echo $beforeEachImage . $matches[1][$i] . $afterEachImage;
}
?>

Thank you for advice. Now I replaced code like this. Now replaced line shows errors.

<?php
$beforeEachImage = "<div>";
$afterEachImage = "</div>";
preg_match_all("/(<img [^>]*>)/",auto_alt_set(get_the_content()),$matches,PREG_PATTERN_ORDER);
for( $i=0; isset($matches[1]) && $i < count($matches[1]); $i   ) {
echo $beforeEachImage . $matches[1][$i] . $afterEachImage;
}
?>

CodePudding user response:

preg_match_all("/(<img [^>]*>)/", auto_alt_set(get_the_content()), $matches, PREG_PATTERN_ORDER);
  • Related