為了提升SEO效果,金合發麻將我們通常會為圖片添加 alt 和 title 屬性,但手動一個個添加實在太麻煩了。因此,我們可以透過程式碼讓 WordPress 自動為圖片添加這些屬性,這樣更省事。
在你所使用的 WordPress 主題中的 functions.php 檔案的最後一個 ?> 標籤前,娛樂網加入以下程式碼即可實現自動為 WordPress 網站圖片新增 alt 和 title 屬性:
/**
* 自動為圖片新增 alt 和 title 屬性
*/
function image_alt_title( $content ) {
global $post;
$category = get_the_category();
$fl_name = $category[0]->cat_name;
$blog_title = get_bloginfo();
$img_title = $post->post_title;
$img_url = ‘<img\s[^>]*src=(“??)([^” >]*?)\\1[^>]*>’;
if ( preg_match_all( “/$img_url/siU”, $content, $matches, PREG_SET_ORDER ) ) {
if ( ! empty( $matches ) ) {
for ( $i = 0; $i < count( $matches ); $i++ ) {
$tag = $url = $matches[$i][0];
$j = $i + 1;
$judge = ‘/title=/’;
preg_match( $judge, $tag, $match, PREG_OFFSET_CAPTURE );
if ( count( $match ) < 1 ) {
$alt_title = ‘ alt=”‘ . $img_title . ‘ ‘ . $fl_name . ‘ 第’ . $j . ‘張” title=”‘ . $img_title . ‘ ‘ . $fl_name . ‘ 第’ . $j . ‘張- ‘ . $blog_title . ‘” ‘;
}
$url = rtrim( $url, ‘>’ );
$url .= $alt_title . ‘>’;
$content = str_replace( $tag, $url, $content );
}
}
}
return $content;
}
add_filter( ‘the_content’, ‘image_alt_title’ );
於 alt 和 title 屬性:
title 屬性:主要是為了使用者體驗,玖天娛樂城評價當使用者將滑鼠懸停在圖片上時,會顯示 title 屬性中的文字。
alt 屬性:主要是為了搜尋引擎優化,同時也有助於使用者體驗。當圖片無法載入時,會顯示 alt 屬性中的文字。現金版 註冊送另外,alt 屬性也是搜尋引擎爬蟲辨識圖片內容的重要方式。
一個完善的優化過的圖片應該同時具備 title 屬性和 alt 屬性,註冊就送體驗金而且 alt 屬性中最好包含文章的關鍵字,以提升圖片在搜尋引擎中的可見性和相關性。