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.
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.
Share Improve this question asked Oct 11, 2019 at 16:46 pjk_okpjk_ok 9082 gold badges15 silver badges36 bronze badges1 Answer
Reset to default 3<?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)