How to set Custom Excerpt and Content Limit WordPress?

All QuestionsCategory: WordPressHow to set Custom Excerpt and Content Limit WordPress?
S M Hasibul Islam Staff asked 4 years ago

What I want to know is how you can have multiple of these each returning different numerical values so I can get short excerpts for sidebar loops, longer excerpts for featured loops, and the longest excerpt for the main article.
 

S M Hasibul Islam Staff replied 4 years ago

I got another way to display limited excerpt by character. Here is the functions.php file code.

2 Answers
S M Hasibul Islam Staff answered 4 years ago

I just found a solution to limiting the number of words in the excerpt without plugins. Add the following code to your functions.php file.

<?php
// Custom Excerpt
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'...';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
return $excerpt;
}

// Content Limit
function content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('/\[.+\]/','', $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
return $content;

?>

Now, instead of using the_content() or the_excerpt in your loop, use excerpt($limit) or content($limit). If you want to limit your excerpt to 25 words the code would look like this:

<?php echo excerpt(25); ?>
bdonlinebazar replied 4 years ago

very helopfull

Hasibul Islam Badsha replied 4 years ago

nice!!!

S M Hasibul Islam Staff answered 4 years ago

I got another way to display limited excerpt by character. Here is the functions.php file code.

function get_excerpt(){
$excerpt = get_the_content();
$excerpt = preg_replace(" (\[.*?\])",'',$excerpt);
$excerpt = strip_shortcodes($excerpt);
$excerpt = strip_tags($excerpt);
$excerpt = substr($excerpt, 0, 100);
$excerpt = substr($excerpt, 0, strripos($excerpt, " "));
$excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt));
$excerpt = $excerpt.'... <a href="'.get_the_permalink().'">Read More</a>';
return $excerpt;
}

After this you need to add where you want to display your customized character by character.

<?php echo get_excerpt(); ?>