Tự động set ảnh đầu tiên là featured image cho module auto-upload-images

Sửa đoạn cuối, sau hàm foreach trong hàm save() trong  /wp-content/plugins/auto-upload-images/src/WpAutoUpload.php

  1. $success = (bool) $wpdb->update($wpdb->posts, array('post_content' => $content), array('ID' => $post->ID));
  2. $thumb_id = 0;
  3. $thumb_id = $this->get_first_content_image_id( $content );
  4. if ($thumb_id > 0)
  5. update_post_meta( $post->ID, '_thumbnail_id', $thumb_id );
  6.  
  7. return $success;

Và thêm hàm get_first_content_image_id trong file đó

  1. private function get_first_content_image_id ( $content ) {
  2. // set variables
  3. global $wpdb;
  4. // look for images in HTML code
  5. preg_match_all( '/<[iI][mM][gG][^>]+>/', $content, $all_img_tags );
  6. if ( $all_img_tags ) {
  7. foreach ( $all_img_tags[ 0 ] as $img_tag ) {
  8. // find class attribute and catch its value
  9. preg_match( '/<img[^>]*class\s*=\s*[\'"]([^\'"]+)[\'"][^>]*>/i', $img_tag, $img_class );
  10. if ( $img_class ) {
  11. // Look for the WP image id
  12. preg_match( '/wp-image-([\d]+)/i', $img_class[ 1 ], $found_id );
  13. // if first image id found: check whether is image
  14. if ( $found_id ) {
  15. $img_id = absint( $found_id[ 1 ] );
  16. // if is image: return its id
  17. if ( wp_attachment_is_image( $img_id ) ) {
  18. return $img_id;
  19. }
  20. } // if(found_id)
  21. } // if(img_class)
  22.  
  23. // else: try to catch content image id by its url as stored in the database
  24. // find src attribute and catch its value
  25. preg_match( '/<img[^>]*src\s*=\s*[\'"]([^\'"]+)[\'"][^>]*>/i', $img_tag, $img_src );
  26. if ( $img_src ) {
  27. // delete optional query string in img src
  28. $url = preg_replace( '/([^?]+).*/', '\1', $img_src[ 1 ] );
  29. // delete image dimensions data in img file name, just take base name and extension
  30. $guid = preg_replace( '/(.+)-\d+x\d+\.(\w+)/', '\1.\2', $url );
  31. // if path is set relatively make it absolute
  32. if ( 0 === strpos( $guid, '/' ) ) {
  33. $guid = home_url() . $guid;
  34. }
  35. // look up its ID in the db
  36. $found_id = $wpdb->get_var( $wpdb->prepare( "SELECT `ID` FROM $wpdb->posts WHERE `guid` = '%s'", $guid ) );
  37. // if first image id found: return it
  38. if ( $found_id ) {
  39. return absint( $found_id );
  40. } // if(found_id)
  41.  
  42. } // if(img_src)
  43. } // foreach(img_tag)
  44. } // if(all_img_tags)
  45.  
  46. // if nothing found: return 0
  47. return 0;
  48. }

 

 

Leave a Reply

You must be logged in to post a comment.