WordPress excerpt is an optional summary or short description of the post. You can use post excerpt to display post summary on archive pages and search page. You can use the_excerpt(); to display post excerpt. You might want to display post excerpt of different length for different post types based on the layout of displaying posts. You can use the function as 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 '' . esc_html( $excerpt ) . '
';