drrobotnik
5/20/2014 - 6:27 PM

get first image in post set/delete all post thumbnails

get first image in post set/delete all post thumbnails

/**
 * Grab first image from $post->post_content
 *
 * @since 1.0
 *
 * @return   string
 */
function cv_post_first_image( $post_obj = null ) {
  if( empty($post_obj) )
    global $post;
  else
    $post = $post_obj;

  $first_img = '';
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  if( !empty( $matches[1] ) ){
    $first_img = $matches[1][0];
  }
  $first_img = preg_replace('/\s+/', '', $first_img);
  return $first_img;
}

function cv_post_first_image_by_id( $post_obj = null ){
  if( empty($post_obj) )
    global $post;
  else
    $post = $post_obj;

  $img = cv_post_first_image( $post );
  if( empty($img) )
    return false;

  global $wpdb;

  $prepare = $wpdb->prepare(
    "SELECT id FROM wp_posts
    WHERE post_type='attachment'
    AND guid=%s",
    $img );

  $result = $wpdb->get_col( $prepare, 0 );

  return $result[0];

}

function cv_delete_all_post_thumbnails(){
  global $wpdb;

  $query = "SELECT id FROM wp_posts
    WHERE post_type='post'
    AND post_status='publish'";

  $results = $wpdb->get_results( $query );
  foreach ($results as $result ) {
    delete_post_thumbnail( $result->id );
  }
}

function cv_set_all_post_thumbnails(){
  global $wpdb;

  $query = "SELECT id FROM wp_posts
    WHERE post_type='post'
    AND post_status='publish'";

  $results = $wpdb->get_results( $query );
  foreach ($results as $result ) {
    $thumb_id = cv_post_first_image_by_id( $result->id );
    if( !empty( $thumb_id ) )
      set_post_thumbnail( $result->id, $thumb_id );
  }
}

//add_action( 'wp_head', 'cv_delete_all_post_thumbnails', 100);
//add_action( 'wp_head', 'cv_set_all_post_thumbnails', 100);