Monday 20 January 2014

How To Set Featured Image From Attachment

In WordPress theming featured image functionality helps in displaying unique images for posts, every time we have set a featured image , in order to reduce pain for us, i have found a snippet which helps to make attachment(image) as featured image. Add the following snippet in to your functions.php file.



add_filter('the_content', 'set_attached_imageas_featured');
function set_attached_imageas_featured($content) {
 global $post;
 if (has_post_thumbnail()) {
  // display the featured image
  $content = the_post_thumbnail() . $content;
 } else {
  // get & set the featured image
  $attachments = get_children(array(
   'post_parent' => $post->ID, 
   'post_status' => 'inherit', 
   'post_type' => 'attachment', 
   'post_mime_type' => 'image', 
   'order' => 'ASC', 
   'orderby' => 'menu_order'
  ));
  if ($attachments) {
   foreach ($attachments as $attachment) {
    set_post_thumbnail($post->ID, $attachment->ID);
    break;
   }
   // display the featured image
   $content = the_post_thumbnail() . $content;
  }
 }
 return $content;
}


No comments:

Post a Comment