Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am using this code here:

<?php
$trim_length = 25;  //desired length of text to display
$custom_field = 'my-custom-field-name';
$value = get_post_meta($post->ID, $custom_field, true);
if ($value) {
 echo rtrim(substr($value,0,$trim_length));
}
?>

It works - but I would like to have a "(...)" at the end of the trimmed text. And only if the value really was trimmed.

I used if ($value) { echo rtrim(substr($value,0,$trim_length)) . '(...)'; } ?> But this makes the "(...)" at the end of every text from custom field..

Thank you!

AD

share|improve this question
    
Don’t use strlen() or substr(). –  toscho Jul 14 '12 at 20:26
add comment

3 Answers

up vote 1 down vote accepted

building on keatch's answer you only need to trim if its longer the 25 chars so:

$trim_length = 25;  //desired length of text to display
$custom_field = 'my-custom-field-name';
$value = get_post_meta($post->ID, $custom_field, true);
if ($value) {
    if (strlen($value) > $trim_length)
        $value = rtrim(substr($value,0,$trim_length)) .'(...)';
 echo $value;
}
share|improve this answer
    
thank you very much! that's it! –  ad2003 Jul 14 '12 at 23:00
add comment

Try this code.

You must check if the string was trimmed. If it is, is length is $trim_length So, you must add the '(...)' at the end

<?php
$trim_length = 25;  //desired length of text to display
$custom_field = 'my-custom-field-name';
$value = get_post_meta($post->ID, $custom_field, true);
if ($value) {
 $trimmed_value= rtrim(substr($value,0,$trim_length));
 if (strlen($trimmed_value) >= $trim_length)
    $trimmed_value .= " (...)";
 echo $trimmed_value;
}
?>
share|improve this answer
    
thank you for your reply! –  ad2003 Jul 14 '12 at 23:02
add comment

Since Wordpress 3.3 there is a built-in function for this : wp_trim_words() which accepts as arguments the number of words and the chain the add if trimmed.

So you could do something like :

 <?php
  $trim_length = 25;  //desired length of text to display
  $value_more = '(...)'; // what to add at the end of the trimmed text
  $custom_field = 'my-custom-field-name';
  $value = get_post_meta($post->ID, $custom_field, true);
   if ($value) {
      echo wp_trim_words( $value, $trim_length, $value_more);
   }
   ?>
share|improve this answer
    
thank you for your reply! –  ad2003 Jul 14 '12 at 23:02
    
You're welcome ^^ –  Simon Jul 15 '12 at 23:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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