Last active
May 17, 2016 19:43
-
-
Save mathetos/30d539fda8a195a90087 to your computer and use it in GitHub Desktop.
Smart Excerpts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* This asks first for a Yoast SEO meta description, | |
* If that's not present, then it asks for the excerpt of the post, | |
* If that's not present, then it strips the content | |
* In this case, I have an excerpt length setting in the Customizer | |
* Both the excerpt and content stripping, also strip shortcodes | |
* @author Matt Cromwell <[email protected]> | |
* @copyright Copyright (c) 2014, Matt Cromwell | |
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License | |
*/ | |
//Definitions | |
$yoastdesc = get_post_meta(get_the_ID(), '_yoast_wpseo_metadesc', true); | |
$excerptlength = get_theme_mod('excerpt_length', 25); | |
$excerpt = get_the_excerpt(); | |
$content = get_the_content(); | |
$screenreader = '<a href="' . get_permalink() . '"><span class="screen-reader-text">' . get_the_title( ) . '</span>Read More …</a>'; | |
//Check for Yoast meta description first | |
if(!empty($yoastdesc)) { | |
//Trim it according the the excerpt length and include Twenty Fifteen's screenreader markup | |
$trimyoast = wp_trim_words($yoastdesc, $excerptlength, $screenreader); | |
echo $trimyoast; | |
//If that fails, check for a manual excerpt | |
} elseif(has_excerpt() == true) { | |
//Trim that according to the excerpt length | |
//and include Twenty Fifteen's screenreader markup | |
$trimexcerpt = wp_trim_words( $excerpt , $excerptlength, $screenreader ); | |
//There's almost no chance there's shortcodes in there, | |
//but let's be careful and strip 'em out anyway | |
echo strip_shortcodes($trimexcerpt); | |
//If both of those fail, grab the content of the post itself | |
} else { | |
//Trim the content according to the excerpt length | |
//and include Twenty Fifteen's screenreader markup | |
$trimmed_content = wp_trim_words( $content, $excerptlength, $screenreader ); | |
//Shortcodes are VERY likely here, so strip 'em out | |
echo strip_shortcodes($trimmed_content); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I will say additionally that I just today stumbled on the
wp_html_excerpt
function, which will allow me to replace wp_trim_words completely and will be much cleaner. Just not sure when I'll implement that exactly yet...