About design and nearby

How to Shorten WordPress Post Titles

Posted: June 2nd, 2014 | Author: | Filed under: Development | Tags: , , , | No Comments »

If you would like to know how to limit the amount of letters for the title of the WordPress post, this article is for you. Such feature is helpful, indeed – sometimes you may not allow a user to print as many symbols as he tries to, it could break the design.

The idea is pretty simple: in functions.php you create the function by name (in my case) ‘the_title_limit’:

  1. function the_title_limit($length, $replacer = '…') {
  2.  $string = the_title('','',FALSE);
  3.  if(strlen($string) > $length)
  4.  $string = (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
  5.  echo $string;
  6. }


You can set the length of your title later – at the place where you call for ‘the_title_limit’:

  1. <a href="<?php the_permalink(); ?>"><?php the_title_limit(30, '…'); ?></a>

– my title length = 30 symbols.

And thanking to

  1. $replacer = '…'

you add ‘…’ after the shorten title. You can place anything else here (for example, ‘ read more >’).

Example:

How to limit WordPress post title

  1. <?php $latest = new WP_Query( array( 'posts_per_page' => 2, 'offset' => 2 ));
  2. if( $latest->have_posts() ) : ?>
  3. <ul class="recent">
  4. <?php while( $latest->have_posts() ) : $latest->the_post(); ?>
  5. <li>      
  6. <?php if ( has_post_thumbnail()) : ?>
  7. <span class="news-thumb">
  8. <?php the_post_thumbnail(array(120,120)); ?>
  9. </span>              
  10. <?php endif; ?>
  11. <a class="blog-posts" href="<?php the_permalink(); ?>"><?php the_title_limit(30, '…'); ?></a>
  12. <a class="more-link" href="<?php the_permalink(); ?>">Find out more</a>
  13. </li>
  14. <?php endwhile; ?>
  15. </ul>  
  16. <?php endif; wp_reset_postdata(); ?>

You could be interested to read related post: How to Remove Specific Categories from the Loop

Share Button

Check Related Posts:


Leave a Reply


  • six + 1 =

Looking for a Freelance UX & UI designer for your project? I’m ready to jump onboard!

Let's discuss your project now