Limit Query Loop excerpt length without truncating last word
-
I got this code from ChatGPT, but it doesn’t work, and I’m hoping someone here can explain why. The goal is to limit the excerpt block in the query loop to a certain number of characters, but make sure the last word isn’t cut off. That is, the excerpt of the content, and not the manually created excerpt area.
The execution of the code results in the excerpt being blank (i.e., nothing is posted).
// Custom function to limit excerpt length while preserving the last word function custom_excerpt($text, $length) { $excerpt = strip_tags($text); if (strlen($excerpt) > $length) { $excerpt = substr($excerpt, 0, $length); $last_space = strrpos($excerpt, ' '); $excerpt = substr($excerpt, 0, $last_space); $excerpt .= '...'; } return $excerpt; } // Filter the excerpt length using the custom function function custom_excerpt_length($length) { return 144; // Adjust the number to your desired character limit } add_filter('excerpt_length', 'custom_excerpt_length'); // Filter the excerpt output function custom_excerpt_more($more) { return '...'; } add_filter('excerpt_more', 'custom_excerpt_more'); // Filter the excerpt using the custom function function custom_filter_excerpt($excerpt) { global $post; return custom_excerpt($post->post_excerpt, 144); } add_filter('wp_trim_excerpt', 'custom_filter_excerpt');
Thank you.
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘Limit Query Loop excerpt length without truncating last word’ is closed to new replies.