Created
February 26, 2018 05:31
-
-
Save jstnbr/0df5742de63288a9733eb3e0b2572d86 to your computer and use it in GitHub Desktop.
Generate a custom excerpt in Wordpress.
This file contains 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 | |
/** | |
* Custom Excerpt | |
* | |
* @param array $args { | |
* Optional. Array of excerpt() arguments. | |
* | |
* @type int $limit Limit result to amount. Default '55'. | |
* @type string $limitby Limit by either word or character. Default 'word'. Accepts 'char', 'word'. | |
* @type string $append Append a string to the excerpt. Default null. | |
* @type string $source Source to use for the excerpt. Default get_the_excerpt(). | |
* } | |
* @return string $excerpt String of the resulting excerpt. | |
* | |
* $excerpt = array( | |
* 'limit' => 55, | |
* 'limitby' => 'char', | |
* 'append' => '...', | |
* 'source' => $source | |
* ); | |
* | |
*/ | |
function excerpt($args = null) { | |
$defaults = array( | |
'limit' => 55, | |
'limitby' => 'word', | |
'append' => null, | |
'source' => get_the_excerpt() | |
); | |
$args = wp_parse_args($args, $defaults); | |
$excerpt = $args['source']; // Excerpt equal to $source argument | |
$excerpt = strip_shortcodes($excerpt); // Strip shortcodes | |
$excerpt = strip_tags($excerpt); // Strip tags | |
$excerpt = str_replace(array(' '), ' ', $excerpt); // Replace forced space with single space | |
// Limit by character if excerpt length greater than limit | |
if ($args['limitby'] == 'char' && strlen($excerpt) > $args['limit']) { | |
$excerpt = preg_replace('(\[.*?\])', '', $excerpt); | |
$excerpt = substr($excerpt, 0, $args['limit']); | |
$excerpt = substr($excerpt, 0, strripos($excerpt, ' ')); | |
$excerpt = trim(preg_replace('/\s+/', ' ', $excerpt)); | |
$excerpt = $excerpt . $args['append']; | |
// Limit by word if excerpt length greater than limit | |
} else if ($args['limitby'] == 'word' && str_word_count($excerpt) > $args['limit']) { | |
$excerpt = preg_replace('/\s+/', ' ', $excerpt); // Replace multiple spaces into single space | |
$excerpt = explode(' ', $excerpt, $args['limit'] + 1); | |
array_pop($excerpt); | |
$excerpt = implode(' ', $excerpt); | |
$excerpt = $excerpt . $args['append']; | |
} | |
return $excerpt; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment