Two Excerpt Types for Different Categories in WordPress

By default, you can only use one excerpt type in WordPress. You can display a certain number of characters as excerpts, you display your first paragraphs as excerpts, or other excerpt types. You can only use one of these in your WordPress site. This tutorial will teach you how to use two excerpt types for different categories.

Copy the two groups of code below to the functions.php file of your WordPress-built website. Make sure you change the category names used in the code to your website’s category names.

Code 1 – Truncate excerpts and add ‘Read More’ to certain categories

// SITE EXCERPTS - START
// EXCERPT TYPE 1 - Truncate excerpts and add 'Read More' to Categories 'Firstcat','Secondcat','Thirdcat','Fourtcat'
// Truncate excerpt
function custom_excerpt_length( $length ) {
    if (in_category( array( 'Firstcat','Secondcat','Thirdcat','Fourtcat'))) {
return 80; // Number of words to use as an excerpt for each post
}
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
// Add a "Read More" link to the end of an excerpt
function excerpt_read_more( $more ) {
    if (in_category( array( 'Firstcat','Secondcat','Thirdcat','Fourtcat'))) {
return '... <a href="'.get_the_permalink().'" class="readmore">Read More</a>';
}}
add_filter( 'excerpt_more', 'excerpt_read_more' );

Code 1 will display a certain number of words as excerpts in archive pages for posts in the categories ‘Firstcat’, ‘Secondcat’, ‘Thirdcat’, and ‘Fourtcat’.

Code 2 – Display first paragraphs as excerpts for other categories

// EXCERPT TYPE 2 - Display first paragraphs as excerpts for Other Categories
 function wp_custom_excerpt($text, $raw_excerpt) {
    if(( ! $raw_excerpt ) and (! in_category( array( 'Firstcat','Secondcat','Thirdcat','Fourtcat'))) or (is_front_page()) ) {
        $content = apply_filters( 'the_content', get_the_content() );
        $text = substr( $content, 0, strpos( $content, '</p>' ) + 4 );
    }
    $text = preg_replace("/<img[^>]+\>/i", "", $text); 
    return $text;
}
add_filter( 'wp_trim_excerpt', 'wp_custom_excerpt', 10, 2 );
// SITE EXCERPTS - END

Code 2 will display first paragraphs as excerpts for other categories.