问题
I want to trim my title length on related posts and i tried several variations and no one works. I have now this
<p style="margin-top:-4px !important"><a class="title" href="<?php the_permalink() ?>" title="<?php the_title(); ?>">**<?php echo short_title('...', 3); ?>**</a></p>
</li>
<?php
This short_title trims words(now i have value 3 it shows me first 3 words) and I want just characters maybe 20,30 . How do I do this?
回答1:
Use substr()
$title = 'some text here for example';
$newTitle = (strlen($title)>20)?substr($title,0,20):$title;
回答2:
The better way is not to truncate the string, but use CSS features to show ... in case of long text, but leave the text unchanged, because for different fonts/browsers/devivices is impossible to get the same results.
css is:
.long {
width: 50px;
}
.long span {
padding-top: 4px;
display: block;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
html:
<div class="long"><span>Very long text should be truncated</span></div>
来源:https://stackoverflow.com/questions/29413712/how-to-shorten-my-title-lenth-by-characters-via-php-code-wordpress