• Resolved taghaboy

    (@taghaboy)


    hello,
    How can i shorten my title <?php the_title(); ?> using this php script :

    <?php
    function shorten_text($text, $length) {
        $shortened_text = substr($text, 0, $length);
        $shortened_text .= '…';
        return $shortened_text;
    }
    $title = 'Your very long title blah blah blah';
    $shortened_title = shorten_text($title, 15);
    
    print $shortened_title;
    ?>

    Thanks

Viewing 6 replies - 1 through 6 (of 6 total)
  • What do you mean by shorten the title? The title of the post? Just… type a shorter title.

    Thread Starter taghaboy

    (@taghaboy)

    Hi thisisedie,
    cause i’d like to short the title only in frontpage, and show the full in Read more.
    My goal is how can i insert the <?php the_title(); ?>
    in line 7 = ‘Your very long title blah blah blah

    Thanks

    Thread Starter taghaboy

    (@taghaboy)

    any help please.

    For starters, you need the_title in your code:

    <?php $ptitle = the_title("","", false); ?>

    Thread Starter taghaboy

    (@taghaboy)

    I’v find solution in https://www.wordpress-fr.net/support/viewtopic.php?pid=99796#p99796
    and thanks goes to BertrandB21

    <?php
          function shorten_text($text, $length) {
              $shortened_text = substr($text, 0, $length);
              $shortened_text .= '…';
              return $shortened_text;
          }
          if (have_posts()) : while (have_posts()) : the_post();
              $title=the_title('','',FALSE);
              $shortened_title = shorten_text($title, 15);
              print $shortened_title;
          ?>
              <?php endwhile;?>
            <?php else : ?>
              <h2>Introuvable</h2>
              <p>Désolé, mais vous cherchez quelque chose qui n'est pas ici.</p>
          <?php endif; ?>

    also for little code lover you can simply use this:
    <?php $thetitle = $post->post_title; echo substr($thetitle, 0, 26); ?>…

    Enjoy

    Found an even better php function to strip characters without loosing words:

    Copy and paste this into your theme_folder/functions.php file:

    //function to call and print shortened post title
    function the_title_shorten($len,$rep='...') {
    	$title = the_title('','',false);
    	$shortened_title = textLimit($title, $len, $rep);
    	print $shortened_title;
    }
    
    //shorten without cutting full words (Thank You Serzh 'https://us2.php.net/manual/en/function.substr.php#83585')
    function textLimit($string, $length, $replacer) {
    	if(strlen($string) > $length)
    	return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
    	return $string;
    }

    And then call it in your template file:

    <?php the_title_shorten(15,'...'); ?>

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘HELP – how to shorten the_title’ is closed to new replies.