Advertisement
brasofilo

Set first attached image as Featured Image

May 10th, 2012
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.91 KB | None | 0 0
  1. <?php
  2. /*
  3.  * put the code in functions.php
  4.  * visit any admin page in wordpress
  5.  * delete the code
  6.  */
  7. function get_first_image($ID) {
  8.     $args = array(
  9.         'numberposts' => 1,
  10.         'post_mime_type' => 'image',
  11.        'post_parent' => $ID,
  12.         'post_status' => null,
  13.         'post_type' => 'attachment'
  14.         );
  15.         $attachments = get_children( $args );
  16.         if ($attachments) {
  17.             foreach($attachments as $att) return $att->ID;
  18.         }
  19. }
  20. function make_featured_images() {
  21.     // CHANGE THE POST TYPE AS NEEDED
  22.     $posts = get_posts( array('numberposts' => -1, 'post_type' => 'post') );
  23.     foreach ( $posts as $post ) {
  24.         $featured = get_the_post_thumbnail( $post->ID, 'thumbnail', null );
  25.         // WILL NOT RUN IF POST ALREADY HAS A FEATURED IMAGE
  26.         if ( !$featured ) {
  27.             $feat = get_first_image($post->ID);
  28.             if($feat) set_post_thumbnail( $post->ID, $feat );
  29.         }
  30.     }
  31. }
  32. add_action('init', 'make_featured_images');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement