• 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.

    • This topic was modified 7 months, 1 week ago by brentrambo.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi @brentrambo,
    Can you try replacing following code snippet if it works for you? It works for me.

    function custom_excerpt_length($length) {
        return 144; // Change 20 to your desired excerpt length in words
    }
    
    // Filter the excerpt output
    function custom_excerpt_more($more) {
        return '...';
    }
    add_filter('excerpt_more', 'custom_excerpt_more');
    
    function custom_end_excerpt($excerpt) {
        if (has_excerpt() && strpos($excerpt, '</') !== false) {
            $excerpt = substr($excerpt, 0, strrpos($excerpt, '</'));
        }
        return $excerpt;
    }
    
    add_filter('excerpt_length', 'custom_excerpt_length');
    add_filter('wp_trim_excerpt', 'custom_end_excerpt');

    Thanks!

    Thread Starter brentrambo

    (@brentrambo)

    @jeroenrotty thank you for the link, but I don’t know PHP well enough to incorporate the code snippet there into a larger solution.

    @harshgajipara I copied your solution and I got no change. Nothing was different.

    Correction, @harshgajipara, it does change, but it limits to words and not characters.

    • This reply was modified 7 months, 1 week ago by brentrambo.
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.