jan_dembowski

Get first img in post if any

Sep 9th, 2014
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.57 KB | None | 0 0
  1. add_filter( 'the_content' , 'mh_get_first_img' );
  2.  
  3. function mh_get_first_img( $content ) {
  4.  
  5. $mh_url_regex = "/<img\ .*\/\>/";
  6.  
  7. // Get all the matches and populate them in an array
  8. preg_match_all( $mh_url_regex , $content, $mh_matches );
  9.  
  10. if ( $mh_matches[0][0] ) {
  11.         // Zap everything after the first closing '>'
  12.         $mh_first_img = preg_replace( '/>.*$/' , '>', $mh_matches[0][0]);
  13.         // Add the img HTML to the top of the post as an example.
  14.         $content = '<p><pre>' . esc_html( $mh_first_img ) . '</pre></p>' . $content;
  15. }
  16.  
  17. return $content;
  18. }
Advertisement
Add Comment
Please, Sign In to add comment