1

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

1

3 Answers 3

3

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;
}
0
0

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;
}
?>
0
0

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);
   }
   ?>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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