admin管理员组文章数量:1291116
Is there a way to limit the word count of the post title?
I searched over the internet but found nothing.
All I know is, only the content of the post can be limited or excerpted.
Is there a way to limit the word count of the post title?
I searched over the internet but found nothing.
All I know is, only the content of the post can be limited or excerpted.
Share Improve this question edited Dec 11, 2012 at 8:48 fischi 7,5492 gold badges29 silver badges44 bronze badges asked Dec 11, 2012 at 8:18 Juliver GalletoJuliver Galleto 2903 gold badges6 silver badges14 bronze badges4 Answers
Reset to default 8simply use this where ever you want to display your title with limited words
<?php echo wp_trim_words( get_the_title(), 5 ); ?>
replace number 5 in above code with whatever number of words you need to display.
Regards.
If continue sign "..." needed at end of title
<?php
echo wp_trim_words( get_the_title(), 10, '...' );
?>
If continue sign "..." not needed at end of title
<?php
echo wp_trim_words( get_the_title(), 10 );
?>
There is a built-in function for that: wp_trim_words()
.
add_filter( 'the_title', 'wpse_75691_trim_words' );
function wpse_75691_trim_words( $title )
{
// limit to ten words
return wp_trim_words( $title, 10, '' );
}
If you want to trim the words depending on certain properties of the post, ask WP to pass the post ID to your callback. Here is an example for filtering by post type. But you can also check for associated terms, post age or author, and even post meta.
add_filter( 'the_title', 'wpse_75691_trim_words_by_post_type', 10, 2 );
function wpse_75691_trim_words_by_post_type( $title, $post_id )
{
$post_type = get_post_type( $post_id );
if ( 'product' !== $post_type )
return $title;
// limit to ten words
return wp_trim_words( $title, 10, '' );
}
function limit_word_count($title) {
$len = 5; //change this to the number of words
if (str_word_count($title) > $len) {
$keys = array_keys(str_word_count($title, 2));
$title = substr($title, 0, $keys[$len]);
}
return $title;
}
add_filter('the_title', 'limit_word_count');
You can put any kind of limit on almost anything you like, you just need the correct filter
本文标签: Limit the word count in the post title
版权声明:本文标题:Limit the word count in the post title 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741509262a2382509.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论