Featured Image Otomatis pada WordPress

Pada WordPress versi 3.5 keatas, untuk melakukan set featured image (digunakan untuk thumbnails), tidak bisa langsung disekaliguskan pada saat insert image into post.

Sehingga dengan diterapkannya function di bawah ini (pada file function.php), jika melakukan upload image, tidak perlu lagi set featured image, karena telah dilakukan secara otomatis oleh function tersebut.

Dengan begitu, hal ini sedikit meringankan pekerjaan uploader. Walaupun untuk insert image into post yang sudah ada di gallery masih perlu dilakukan manual. It helps a bit! 😀

/**
 * Autoset Featured Image
 *
 * @writer Muhammad Riza Alifi
 * http://wpmu.org/daily-tip-how-to-automatically-set-the-featured-image-in-wordpress/
 */
function autoset_featured() {
  global $post;
  $already_has_thumb = has_post_thumbnail($post->ID);
  if (!$already_has_thumb)  {
    $attached_image = get_children( "post_parent=$post>ID&post_type=attachment&post_mime_type=image&numberposts=1" );
    if ($attached_image) {
      foreach ($attached_image as $attachment_id => $attachment) {
        set_post_thumbnail($post->ID, $attachment_id);
      }
    }
  }
}
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

Published by

Riza

Contemplative Learner

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.