How to customize wordpress image alt tag

In case you want to beautify image alt tag for all your wordpress posts, you can use filter hook the_content. Attach a filter function to the_content filter hook and using regular expressions, modify the img alt tag. E.g. you may want to replace – with space. Here is wordpress php code snippet for doing it:

function the_content_modify_img_alt($content) {
  $newcontent = preg_replace_callback (
    '|<IMG src=[\'"][^\'"]+wp-content/uploads/[^\'"]+[\'"]\s+(ALT=[\'"][-\w]+[\'"])|i',
    function ($matches) {
       $fullmatch = $matches[0];
       $altpart = $matches[1];
       $newaltpart = str_replace("-", " ", $altpart);
       $newfullmatch = str_replace($altpart, $newaltpart, $matches[0]);
       return $newfullmatch;
    },
    $content
  );
  return $newcontent;
}
add_filter('the_content', 'the_content_modify_img_alt');

This code looks for all img tag occurrences and if alt attributes is present and has only alphanumeric and dashes in it, it replaces dash with space. You can add you own custom logic using a similar approach.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments