Tự động thêm thẻ alt text vào hình ảnh trong wordpress


Tự động thêm thẻ alt text vào hình ảnh trong wordpress

92 Likes Comment

Thẻ Alt text là cái mà giúp google sẽ đọc xem ảnh đó nói cái gì. Nếu như bạn viết bài có seo hình ảnh nữa thì bài viết sẽ lên top nhanh hơn.
Nhưng đa phần các bạn đều chỉ upload ảnh lên chứ không thêm thẻ alt text vào cho hình ảnh đó.
Vậy để giải quyết vấn đề này mình xin hướng dẫn các bạn thêm thẻ alt text vào hình ảnh một cách tự động.
Ta thêm đoạn code dưới đây vào file functions.php của theme đang sử dụng.

/* Automatically set the image Title, Alt-Text, Caption & Description upon upload
--------------------------------------------------------------------------------------*/
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 );

  } 
}

Như vậy là xong rồi.

 

Bài viết liên quan

Chủ bút: Lê Tú

Blog mình lập ra nhằm mục đích viết lại những gì mình đã tìm hiểu, đã đọc được trên mạng, qua bạn bè để mai mốt cần tìm khỏi quên, cũng như chia sẻ những thứ mà mình đã sưu tầm được. Vì mình không phải chuyên lập trình website nên một số bài viết còn sai sót mong mọi người góp ý.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *