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.


