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

How to add … after a particular wordcharacter limit to the title

programmeradmin1浏览0评论

I am working on a php code as shown below:

   <div class="case-breaking__content">
        <p><?php echo the_title(); ?></p>
   </div>

The above php code returns the following content:

absv shss xcnx shss hshhs shhsw shshs hsnna hssnnss hssns snnss nnshs sjjjjsjsj nsnnnsns jjsnss snsnns nsnns 

What I want is, after a particular word limit it should display ... Lets say after 8 words it should be like this;

absv shss xcnx shss hshhs shhsw shshs hsnna...

I tried in the following way but it doesn't seem to work:

<div class="case-breaking__content">
p><?php $out = strlen(the_title()) > 50 ? substr(the_title(),0,50)."..." : the_title(); ?></p>
</div>

I am working on a php code as shown below:

   <div class="case-breaking__content">
        <p><?php echo the_title(); ?></p>
   </div>

The above php code returns the following content:

absv shss xcnx shss hshhs shhsw shshs hsnna hssnnss hssns snnss nnshs sjjjjsjsj nsnnnsns jjsnss snsnns nsnns 

What I want is, after a particular word limit it should display ... Lets say after 8 words it should be like this;

absv shss xcnx shss hshhs shhsw shshs hsnna...

I tried in the following way but it doesn't seem to work:

<div class="case-breaking__content">
p><?php $out = strlen(the_title()) > 50 ? substr(the_title(),0,50)."..." : the_title(); ?></p>
</div>
Share Improve this question edited May 9, 2019 at 16:21 norman.lol 3,2413 gold badges30 silver badges35 bronze badges asked May 8, 2019 at 16:10 user5447339user5447339 819 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

the_title() prints/retrieve the title while get_the_title() retrieve the title.

So your code should be something like this.

<div class="case-breaking__content">
<p>
   <?php
       $out = strlen(get_the_title()) > 50 ? substr(get_the_title(),0,50)."..." : get_the_title(); 
       echo $out;
   ?>
 </p>
</div>

Note you can use the_title() but it is not recommended here to keep the code clean.

<div class="case-breaking__content">
<p>
   <?php
       $out = strlen(the_title('', '', false)) > 50 ? substr(the_title('', '', false),0,50)."..." : the_title('', '', false); 
       echo $out;
   ?>
 </p>
</div>

The above code will place ... after 50 characters, However if you want to place it after certain numbers of words, you should go for wp_trim_words().

<div class="case-breaking__content">
   <p>
      <?php echo wp_trim_words(get_the_title(), 8, '...'); ?>
  </p>
</div>

I hope this may help.

To trim by words you can use WordPress' wp_trim_words(). Pass get_the_title() instead of the the_title() to prevent a duplicate echo statement.

<?php echo wp_trim_words( get_the_title(), 8, '...' ); ?>
发布评论

评论列表(0)

  1. 暂无评论