1

I've created a custom category template to display the current category's child categories instead of posts. Child categories are displayed via a custom thumbnail, title and category description.

I have added a function to trim the category description to a predefined number of characters, but I'm not sure which action hook to use.

Here's the function:

function trim_text($input, $length, $ellipses = true, $strip_html = true) {
    //strip tags, if desired
    if ($strip_html) {
        $input = strip_tags($input);
    }

    //no need to trim, already shorter than trim length
    if (strlen($input) <= $length) {
        return $input;
    }

    //find last space within length
    $last_space = strrpos(substr($input, 0, $length), ' ');
    $trimmed_text = substr($input, 0, $last_space);

    //add ellipses (...)
    if ($ellipses) {
        $trimmed_text .= '...';
    }

    return $trimmed_text;
}
1

You don't need an action, but a filter, because you want to do something with the result of a function. The filter is, predictably, called category_description In this way (didn't test it though):

function wpse236947_trim_category_desc ( $desc, $cat_id ) {
    // do your thing
    return $desc;
}
add_filter( 'category_description', 'wpse236947_trim_category_desc' );
  • Thanks, I only want to trim the category description for the child categories displayed using my custom template. Anyway, I just found out about the wp_trim_words() function and and I was able to use it to achieve the result I was looking for. – jrcollins Aug 24 '16 at 12:21
1

When asking the question I wasn't aware of the wp_trim_words() function which does exactly what I want. After removing the custom function from my functions.php file all I had to do was add <?php echo wp_trim_words( $child->description, 15, '...' ); ?> to my custom category template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.