WordPress記事内の画像に記事タイトルのaltをつける founction.php

WordPress記事内の画像に記事タイトルのaltをつける founction.php

ブログ記事のaltって付けるのめんどくさいよね。
function.phpで設定してしまいましょう。

// 記事内の画像に記事タイトルのaltをつける
add_filter('the_content', 'my_img_filter');
function my_img_filter($html) {
  global $post;

  // altを削除
  $result = array();
  preg_match_all('|alt="[^"]*"|U', $html, $result);
  foreach($result[0] as $img_tag) {
    $html = str_replace($img_tag, '', $html);
  }
  $result = array();
  preg_match_all("|alt='[^']*'|U", $html, $result);
  foreach($result[0] as $img_tag) {
    $html = str_replace($img_tag, '', $html);
  }

  // altにタイトルを付加する
  $post_title = get_the_title();
  $html = preg_replace('/(<img.*?)/>/', '$1 alt="'.esc_attr($post_title).'" />', $html);

  return $html;
}
attrip

attrip

考えたことを、記事・AI・音楽に変えて発信しています。

盆栽、音楽、ブログ運営、日々の試行錯誤について書いています。

2010年から発信中

コメントを残す