How to shorten my title lenth by characters via php code wordpress

混江龙づ霸主 提交于 2019-12-13 21:33:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!