Home / Blog / WordPress
,

How to set different excerpt length for different post types?

First published 3 Apr 2018. Tested again in November 2026 on WordPress 7.1.4, WooCommerce 11.2.2 and PHP 8.4.

WordPress excerpt is an optional summary or short description of the post. You can use the post excerpt to display a summary on archive pages and the search page. You can use the_excerpt(); to display post excerpt. You might want to display excerpts of different lengths for different post types based on the layout of displaying posts. You can use the function below to define different post excerpt length for different post types.

Using the excerpt_length Filter

function custom_excerpt_length( $length ) {
    global $post;

    if ( ! $post ) {
        return $length;
    }

    switch ( $post->post_type ) {
        case 'post':
            return 30; // 30 words for standard posts

        case 'page':
            return 50; // 50 words for pages

        case 'portfolio': // custom post type
            return 20;

        case 'product': // WooCommerce products
            return 15;

        default:
            return 55; // WordPress default
    }
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Alternative: Using is_singular() or Query Conditionals

function custom_excerpt_length( $length ) {
    global $post;

    if ( ! $post ) {
        return $length;
    }

    if ( $post->post_type === 'portfolio' && is_archive() ) {
        return 15;
    }

    if ( $post->post_type === 'portfolio' && is_singular() ) {
        return 40;
    }

    return 55;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Manually Generating Excerpts by Length (More Control)

If you need precise character/word control beyond the filter, use wp_trim_words() directly in your template files:

// In your template (e.g., archive.php, content.php)
$post_type   = get_post_type();
$word_counts = [
    'post'      => 30,
    'portfolio' => 20,
    'product'   => 15,
];

$length  = $word_counts[ $post_type ] ?? 55;
$excerpt = wp_trim_words( get_the_content(), $length, '...' );

echo '<p>' . esc_html( $excerpt ) . '</p>';

View or fork this snippet on GitHub Gist.

To add a Read more link after the excerpt, see Display a Read More link in WordPress Excerpts.

Need this done on a live site? Exivon Tech takes on projects and audits, led by me.

Dhiren Patel

Principal Full-Stack Engineer · Founder, Exivon Tech

I’ve built and run enterprise web platforms and e-commerce for 13 years, and I built ShieldScope, a free WordPress security scanner, and Lede, a free block theme.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.