Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function custom_get_post_thumbnail_id( $thumbnail_id, $post ) {
- if ( ! $thumbnail_id ) {
- if ( $post && 'post' === $post->post_type ) {
- preg_match_all( '/<img[^>]+>/i', $post->post_content, $img_matches );
- if ( isset( $img_matches[0] ) && count( $img_matches[0] ) > 0 ) {
- $first_img = $img_matches[0][0];
- preg_match( '/src="([^"]+)/i', $first_img, $img_src );
- $img_url = str_ireplace( 'src="', '', $img_src[0] );
- $img_url_no_size = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif))/i', '', $img_url );
- $attachment_id = attachment_url_to_postid( $img_url_no_size );
- if ( $attachment_id ) {
- return $attachment_id;
- }
- }
- }
- }
- return $thumbnail_id;
- }
- add_filter( 'post_thumbnail_id', 'custom_get_post_thumbnail_id', 10, 2 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement