trim custom field text value and show (…)

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.

Read More

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

Related posts

Leave a Reply

3 comments

  1. 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;
    }
    
  2. 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;
    }
    ?>
    
  3. 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);
       }
       ?>