Skip to content

Instantly share code, notes, and snippets.

@stevengliebe
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevengliebe/bb2597803ce1c65da549 to your computer and use it in GitHub Desktop.
Save stevengliebe/bb2597803ce1c65da549 to your computer and use it in GitHub Desktop.
Filter the_excerpt to show content in a more ideal way. Notes here: http://stevengliebe.com/2015/02/26/excerpts-and-the-more-tag-in-wordpress-themes/
<?php
/**
* Filter the_excerpt to show content in a more ideal way.
*
* The way content is shown depends on the priority of a situation:
*
* 1. the_content with "Read More" link if the "More" tag is used
* 2. Manual excerpt with "Read More" link if excerpt is manually entered
* 3. the_content in its entirety if less than 200 words (nicer than automatic excerpt)
* 4. Automatic excerpt with "Read More" link if no better situation
*
* This is based on the handling of excerpts in churchthemes.com themes with improvements inspired
* by Devin Price and commenters: http://wptheming.com/2015/01/excerpt-versus-content-for-archives/
*
* @global object $post
* @param string $excerpt Excerpt from get_the_excerpt()
* @return string Modified excerpt
*/
function themeslug_the_excerpt( $excerpt ) {
global $post;
$show_excerpt = false;
// "Read More" text
/* translators: %s is post title (hidden, for screen readers) */
$more_text = sprintf(
__( 'Read More %s', 'themeslug' ),
the_title( '<span class="screen-reader-text">&mdash; ', '</span>', false )
);
// 1. the_content with "Read More" link if the "More" tag is used, but not password-protected
// This is first because it is as intentional as manual excerpt but manual excerpt could have other purpose (ie. meta description)
if ( strpos( $post->post_content, '<!--more-->' ) && ! post_password_required() ) {
the_content( $more_text );
}
// 2. Manual excerpt with "Read More" link if excerpt is manually provided
elseif ( has_excerpt() ) {
$show_excerpt = true;
}
// 3. the_content in its entirety if less than 200 words, but not password-protected (nicer than automatic excerpt)
// A nice-looking fallback for when they do not use "more" or manual excerpt, or if only published a media embed
elseif ( str_word_count( $post->post_content ) < 200 && ! post_password_required() ) {
the_content();
}
// 4. Automatic excerpt if no better situation
else {
$show_excerpt = true;
}
// Show excerpt with "Read More"
if ( $excerpt && $show_excerpt ) {
?>
<?php
// Manual or automatic excerpt
echo $excerpt;
?>
<p>
<?php
// "Read More" linked
printf(
'<a href="%1$s" class="more-link" rel="bookmark">%2$s</a>',
esc_url( get_permalink() ),
$more_text
);
?>
</p>
<?php
}
}
add_filter( 'the_excerpt', 'themeslug_the_excerpt' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment