最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Limit the Title Length on Custom Post Type Archive Page to a Set Number of Characters

programmeradmin0浏览0评论

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 badges
Add a comment  | 

1 Answer 1

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)

发布评论

评论列表(0)

  1. 暂无评论