WordPress上傳圖片時(shí)圖片不會(huì)自動(dòng)添加ALT和TITLE,這樣非常不利于SEO優(yōu)化,手動(dòng)添加又非常免費(fèi)??棄?mèng)無(wú)憂分享一段WordPress圖片自動(dòng)添加Alt和title方法。
將下面的代碼添加到當(dāng)前主題函數(shù)模板functions.php中:
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' ); function my_set_image_meta_upon_image_upload( $post_ID ) { // Check if uploaded file is an image, else do nothing if ( wp_attachment_is_image( $post_ID ) ) { $my_image_title = get_post( $post_ID )->post_title; // Sanitize the title: remove hyphens, underscores & extra spaces: $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title ); // Sanitize the title: capitalize first letter of every word (other letters lower case): $my_image_title = ucwords( strtolower( $my_image_title ) ); // Create an array with the image meta (Title, Caption, Description) to be updated // Note: comment out the Excerpt/Caption or Content/Description lines if not needed $my_image_meta = array( 'ID'=> $post_ID,// Specify the image (ID) to be updated 'post_title'=> $my_image_title,// Set image Title to sanitized title 'post_excerpt'=> $my_image_title,// Set image Caption (Excerpt) to sanitized title 'post_content'=> $my_image_title,// Set image Description (Content) to sanitized title ); // Set the image Alt-Text update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title ); // Set the image meta (e.g. Title, Excerpt, Content) wp_update_post( $my_image_meta ); } }
代碼可以過(guò)濾掉圖片名稱中的空格等多余元素,對(duì)之前上傳的圖片無(wú)效。
版權(quán)聲明: 本站資源均來(lái)自互聯(lián)網(wǎng)或會(huì)員發(fā)布,如果侵犯了您的權(quán)益請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)刪除!謝謝!
轉(zhuǎn)載請(qǐng)注明: WordPress圖片自動(dòng)添加Alt和title