Skip to content

Instantly share code, notes, and snippets.

@avenirer
Last active August 21, 2018 15:46
Show Gist options
  • Save avenirer/8b79dbdac150480f104e9089bfd3b7c0 to your computer and use it in GitHub Desktop.
Save avenirer/8b79dbdac150480f104e9089bfd3b7c0 to your computer and use it in GitHub Desktop.
WordPress - This snippet, added in functions or where-ever, allows you to select the length and the link title of the excerpt
<?php
// CUSTOMIZE EXCERPT LENGTH
function get_the_excerpt_limit($charlength = 200, $post = null, $readMoreStr = '[...]')
{
$newExcerpt = '';
if(isset($post)) {
$excerpt = strlen($post->post_excerpt) > 0 ? $post->post_excerpt : wp_strip_all_tags($post->post_content);
}
else {
$excerpt = get_the_excerpt();
}
$permalink = isset($post) ? get_the_permalink($post->ID) : get_the_permalink();
$charlength++;
if (mb_strlen($excerpt) > $charlength) {
$newExcerpt = mb_substr($excerpt, 0, $charlength - strlen($readMoreStr));
$exwords = explode(' ', $newExcerpt);
$excut = -(mb_strlen($exwords[count($exwords) - 1]));
if ($excut < 0) {
$newExcerpt = mb_substr($newExcerpt, 0, $excut);
}
$newExcerpt = trim($newExcerpt, ",. \t\n\r\0\x0B") . '... <a href="'.$permalink.'" class="excerpt-read-more">'.$readMoreStr.'</a>';
} else {
$newExcerpt .= trim($excerpt, ",. \t\n\r\0\x0B") . '... <a href="'.$permalink.'" class="excerpt-read-more">'.$readMoreStr.'</a>';
}
return $newExcerpt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment