You can use filters to change the excerpt length. (It goes in your theme or child theme’s functions.php)
function wpdocs_custom_excerpt_length( $length ) {
return 70;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );
At this point I usually also like to change the part that gets added to the end of a truncated excerpt to something like ‘…’
function wpdocs_excerpt_more( $more ) {
return '...';
}
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );
If you want this to only happen on your homepage, you can use the is_page(title/slug/id) function as follows:
function wpdocs_custom_excerpt_length( $length ) {
return 70;
}
function wpdocs_excerpt_more( $more ) {
return '...';
}
function homepageCustomExcerpt() {
if (is_page('home')) {
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );
}
}
add_action( 'init', 'homepageCustomExcerpt' );
The reason for calling the homepageCustomExcerpt
function with add_action( 'init', 'homepageCustomExcerpt' )
is because if is_page()
fires too early, the page would not yet be set and it will always return false.