Reputation: 315
Through research, I've discovered this question has been asked on multiple occasions, however, my instance is a bit different. I'm attempting to add a character limit to a pre-existing customer environment with the following elseif:
elseif(get_post_type() == 'post') {
echo '<p class="excerpt">';
the_excerpt();
echo '</p>';
}
I attempted to use a couple of methods through functions, however, I've been unable to find a resolution. I'm not natively a PHP developer, so I'm learning as I go here and hoping a fellow develop can help resolve this question and provide a brief description of how to handle this in the future.
Thanks!
P.S. - I read the documentation here: http://codex.wordpress.org/Conditional_Tags and wasn't able to make it work without breaking the rest of the else statement.
Upvotes: 0
Views: 1533
Reputation: 11383
Use get_the_excerpt
to return the text without printing it, and chop it to the length you want with substr
:
elseif(get_post_type() == 'post') {
echo '<p class="excerpt">';
$excerpt = get_the_excerpt();
$limit = 100;
if (strlen($excerpt) > $limit) {
echo substr($excerpt, 0, $limit), '[...]';
} else {
echo $excerpt;
}
echo '</p>';
}
Upvotes: 1
Reputation: 10190
Lots of ways to do this.
Easy Way:
Install the Advanced Excerpt plugin and replace the_excerpt();
with the_advanced_excerpt()
and configure as needed in Settings -> Excerpt in admin panel (or use string query vars in the function call). This also lets you do a lot of stuff like have custom "read more" link (or exclude it), add '...' or some other text at the end, strip or allow specific html tags, etc.
Tedious Way:
You can use substr
PHP function (docs) in conjunction with get_the_content();
or get_the_excerpt()
to trim it to however many characters you want (or do whatever else you want to it) like freejosh's answer.
Advanced / Clean Way:
Filter the excerpt length to however many characters you want using the method described in Srikanth's answer (this is my preferred way, unless you need some of the Advanced Excerpt options like use_words
etc).
Upvotes: 0
Reputation: 1854
By default, excerpt length is set to 55 words. To change excerpt length to 20 words using excerpt_length filter, add the following code to functions.php file in your theme:
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
http://codex.wordpress.org/Function_Reference/the_excerpt
Upvotes: 2