1

I have a custom post type 'news' and would like to limit the title character length to 42 characters on the custom post type archive page for 'news'

The following code is how the title is displayed on the archive page for this CPT

<h2><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h2>

Do I pass a parameter into the_title() function, there doesn't seem to be any info suggesting you do this on the codex, or will I do it in my functions.php file?

Many thanks in advance.

2
<?php echo substr(get_the_title(), 0,42) ;?>

Notice the echo and the get_the_title()

This will get you the result you're looking for.


Here's an alternative to consider:

I've always found character limits cause weird word breaks that users find confusing.

WordPress has a function called wp_trim_words that you can use.

<?php echo wp_trim_words( get_the_title(), 5, '...' ); ?>

5 - the number of words you want to show

'...' - the trail after the last word shown (so you could have '- cont.d' or '...read more' or something)

  • The client wants characters and not words, but this is a good answer so I've given it an upvote. What I want is to be able to trim/limit the characters and only add the '...' when it's more than 42 characters. – The Chewy Oct 12 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.