Advertisement
arie_cristianD

get thumbnail image from first image

Aug 13th, 2024 (edited)
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.78 KB | None | 0 0
  1. function custom_get_post_thumbnail_id( $thumbnail_id, $post ) {
  2.     if ( ! $thumbnail_id ) {
  3.         if ( $post && 'post' === $post->post_type ) {
  4.             preg_match_all( '/<img[^>]+>/i', $post->post_content, $img_matches );
  5.  
  6.             if ( isset( $img_matches[0] ) && count( $img_matches[0] ) > 0 ) {
  7.                 $first_img = $img_matches[0][0];
  8.                 preg_match( '/src="([^"]+)/i', $first_img, $img_src );
  9.                 $img_url         = str_ireplace( 'src="', '', $img_src[0] );
  10.                 $img_url_no_size = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif))/i', '', $img_url );
  11.                 $attachment_id   = attachment_url_to_postid( $img_url_no_size );
  12.                 if ( $attachment_id ) {
  13.                     return $attachment_id;
  14.                 }
  15.             }
  16.         }
  17.     }
  18.  
  19.     return $thumbnail_id;
  20. }
  21. add_filter( 'post_thumbnail_id', 'custom_get_post_thumbnail_id', 10, 2 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement