我正在学习本教程—Display Your Popular Posts In WordPress Without A Plugin“并希望限制标题中显示的最大字符数。此外,为什么缩略图有时小于我在php中定义的数字?
如何限制标题中显示的最大字符数
3 个回复
SO网友:Bainternet
首先将此函数添加到函数中。php文件
function max_title_length($title){
$max = 20;
return substr( $title, 0, $max ). " …";
}
然后在链接的代码循环之前添加此行以钩住上述函数:add_filter( \'the_title\', \'max_title_length\');
循环后,移除此过滤器:remove_filter( \'the_title\', \'max_title_length\');
只要改变一下$max = 20;
去你想要的任何地方。SO网友:davidcondrey
您可以使用此位限制显示的字符数并附加省略号。
在这个特定的示例中,我将其设置为trunicate,长度为38个字符,并且仅当标题为trunicate时才显示省略号。无论长度如何,在single\\u post页面上显示完整标题。
<?php
//assign the title to a variable
$the_title = esc_attr ( the_title_attribute ( \'echo=0\' ) );
//specify our desired max character count
$max_length = 38;
//strlen gets the length of the string
$title_length = strlen ( $the_title );
// check if the length of the string is greater than our assigned max length
if ( $title_length > $max_length ) {
// if it is display a substring of the title from the
// first character to the 38th character and append ...
$title_excerpt = substr ( $the_title, 0, $max_length ) . \'...\';
} else {
// otherwise just return the_title()
$title_excerpt = $the_title;
} ?>
<h1 class="entry-title">
<?php if ( is_single () ) { // If article page
the_title ();
} else { // If homepage
?>
<a href="<?php the_permalink (); ?>" title="<?php echo esc_attr ( the_title_attribute ( \'echo=0\' ) ); ?>" rel="bookmark"><?php echo $title_excerpt; ?></a>
<?php } ?>
</h1>
SO网友:Manolo
我改进了@Bainternet答案,使其只显示...
当标题长度超过$max
:
function max_title_length( $title ) {
$max = 30;
if( strlen( $title ) > $max ) {
return substr( $title, 0, $max ). " …";
} else {
return $title;
}
}
然后你可以这样钩住:add_filter( \'the_title\', \'max_title_length\');
结束