Skip to content

Instantly share code, notes, and snippets.

@dannyb195
Created July 13, 2015 17:40
Show Gist options
  • Save dannyb195/3f31bb533954a0c77cad to your computer and use it in GitHub Desktop.
Save dannyb195/3f31bb533954a0c77cad to your computer and use it in GitHub Desktop.
excerpt with image is the image is the first thing in the post
/**
* [the_custom_excerpt description]
* @param [type] $post_content [description]
* @return [type] [description]
*/
function get_the_custom_excerpt( $post_content ) {
$caption_img = '';
$excerpt = '';
// checking for a caption
preg_match( "#(\[caption)([\s\S]+)(\[/caption\])#", $post_content, $caption_match );
$caption_pos = strpos( $post_content, '[caption' );
if ( 0 == $caption_pos && false != $caption_match ) {
// we have an image with a caption at the start of the post
$para1 = explode( $caption_match[0], $post_content ); // isolating the caption shortcode
$para2 = explode( "\n", $para1[1] ); // exploding the content again
// removing empty lines
foreach ( $para2 as $k => $v ) {
if ( 0 == strlen( $v ) || 1 == strlen( $v ) ) {
unset( $para2[ $k ] );
}
}
// resetting array keys
$para2 = array_values( $para2 );
return $caption_match[0] . "\n" . $para2[0];
} else {
// we have an image without a caption at the start of the post
// breaking into array
$para = explode( "\n", $post_content );
// removing empty lines
foreach( $para as $k => $v ) {
if ( 1 == strlen( $v ) ) {
unset( $para[ $k ] );
}
}
foreach( $para as $k => $v ) {
if ( 0 == $k && false != strpos( $v, '<img' ) ) {
return $para[0] . "\n" . $para[1];
} else {
return $para[0];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment