-1

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>
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.

1

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, '...' ); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.