Skip to content

Instantly share code, notes, and snippets.

@ashleyfae
Created March 29, 2016 13:28
Show Gist options
  • Save ashleyfae/3fb6f83228f61b3225b5 to your computer and use it in GitHub Desktop.
Save ashleyfae/3fb6f83228f61b3225b5 to your computer and use it in GitHub Desktop.
Create your own excerpt
<?php
/**
* Create your own custom excerpt for blog posts.
*
* Usage: echo my_custom_excerpt();
* Or, with a modified length: echo my_custom_excerpt( 100 );
*
* @param int $length Desired number of words to display
* @param string $more Characters you want to appear at the end of the excerpt
*
* @return string
*/
function my_custom_excerpt( $length = 55, $more = '...' ) {
global $post; // Get the current post
$post_content = $post->post_content;
/*
* Uncomment this if you want to apply all the_content filters. This may include things
* like social share icons, etc. so I don't totally recommend this.
*/
//$post_content = apply_filters( 'the_content', $post_content );
// Make shortcodes work. If you uncommented the above line then you DON'T need this too.
$post_content = do_shortcode( $post_content );
/*
* Want to strip some HTML tags out? Uncomment this.
* The second paramter should be a bunch of tags that you DON'T want to strip out.
* Everything else will be removed.
*/
//$post_content = strip_tags( $post_content, '<br><p>' );
/*
* Now we cut the content down to your desired length and append the $more string.
*
* translators: If your word count is based on single characters (e.g. East Asian characters),
* enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
* Do not translate into your own language.
*/
if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
$excerpt = trim( preg_replace( "/[\n\r\t ]+/", ' ', $post_content ), ' ' );
preg_match_all( '/./u', $excerpt, $words_array );
$words_array = array_slice( $words_array[0], 0, $length + 1 );
$sep = '';
} else {
$words_array = preg_split( "/[\n\r\t ]+/", $post_content, $length + 1, PREG_SPLIT_NO_EMPTY );
$sep = ' ';
}
if ( count( $words_array ) > $length ) {
array_pop( $words_array );
$excerpt = implode( $sep, $words_array );
$excerpt = $excerpt . $more;
} else {
$excerpt = implode( $sep, $words_array );
}
// We use this to make sure none of our HTML tags got cut off.
$excerpt = force_balance_tags( $excerpt );
// Return the new excerpt.
return $excerpt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment