Limit characters in post_meta (wordpress)

How can I limit the characters in this code?

.get_post_meta($post->ID,'smple1',true).

I have tried with the following:

Read More
$trim_length = 21;  //desired length of text to display 
$custom_field = 'smple1';  
$value = get_post_meta($post->ID, $custom_field, true);    
if ($value) {    
  echo '.rtrim(substr($value,0,$trim_length)) . ';  
}

But I get server error. I must be missing an endif or something?

Many thanks.

Related posts

Leave a Reply

3 comments

  1. You need to fetch the meta value, make sure that it was in false and then use substr() to get the 21 characters, or fewer if the field is shorter based on the results of strlen().

    $length = 21;
    $custom_field = 'smple1';
    
    $value = get_post_meta( $post->ID, $custom_field, true );
    if ( false !== $value ){
        echo substr( $value, 0, (strlen($value) < $length)? strlen($value) : $length );
    }
    
  2. Display no of character using your custom meta key’s value:

    <?php
          $trim_length = 21;
          $custom_field = 'lp_sub_description';  
          $value = get_post_meta($post->ID, $custom_field, true);    
          if ($value) {    
            $data = rtrim(substr($value,0,$trim_length));
            echo $data;  
           } 
    ?> 
    

    Also use simple code :

    <?php echo substr(get_post_meta($post->ID, 'lp_sub_description', true), 0, 21); ?>
    
  3. Ok after many tests it worked in my case as following:

    $filetext = (get_post_meta($post->ID, "smple1", true));
    '.substr($filetext, 0, 8) . "...".'
    

    note when to put '. and .'