I’m currently creating a WordPress theme and I have an area which displays the headline and an excerpt, however the excerpt will need to be a different length depending how long headline (i.e. the headline and excerpt both occupy a fixed space). Therefore I need a way of dynamically changing the excerpt length depending on how long the post title is.
I’ve seen two snippets of code which may be of use. The first is given below:
<?php
// Variable & intelligent excerpt length.
function print_excerpt($length) { // Max excerpt length. Length is set in characters
global $post;
$text = $post->post_excerpt;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
}
$text = strip_shortcodes($text); // optional, recommended
$text = strip_tags($text); // use ' $text = strip_tags($text,'<p><a>'); ' if you want to keep some tags
$text = substr($text,0,$length);
$excerpt = reverse_strrchr($text, '.', 1);
if( $excerpt ) {
echo apply_filters('the_excerpt',$excerpt);
} else {
echo apply_filters('the_excerpt',$text);
}
}
// Returns the portion of haystack which goes until the last occurrence of needle
function reverse_strrchr($haystack, $needle, $trail) {
return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
This can then simply be used e.g. <?php print_excerpt(50); ?>. The code below changes the excerpt length based on the title length. How would I go about combining these two pieces of code?
<?php
// Dynamically resize excerpt according to title length
$rem_len = ""; //clear variable
$title_len = strlen($post->post_title); //get length of title
if($title_len <= 35){
$rem_len=188; //calc space remaining for excerpt
}elseif($title_len <= 70){
$rem_len=146;
}elseif($title_len <= 105){
$rem_len=104;
}elseif($title_len <= 140){
$rem_len=62;
}
$trunc_ex = substr($post->post_excerpt, 0, $rem_len); //truncate excerpt to fit remaining space
if(strlen($trunc_ex) < strlen($post->post_excerpt)) $trunc_ex = $trunc_ex . " [...]";
echo "<p>" . $trunc_ex . "</p>"; //display excerpt
?>
Solved: