• Resolved Rose

    (@eos-rose)


    I have a custom field called “Summary”, which has content summaries of varying length. I need to cut off the text of this field at 150 characters on my index page so that the text doesn’t overflow. This is the code I’m using:

    if(!function_exists('summary_excerpt')){
    	function summary_excerpt(){
    		global $post;
    		$trim_length = 150;  //desired length of text to display
    		$summary_excerpt = 'Summary';
    		$value = apply_filters('the_content', get_post_meta($post->ID, $summary_excerpt, true));
    		if ($value) {
    		  echo rtrim(substr($value,0,$trim_length)).'...';
    		}
    	}
    }

    My issue is that the “…” prints even when my summaries are less than 150 characters, which looks really weird. Is there a way to indicate that the “…” following my summary excerpt should only display when the summary is longer than 150 characters?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    something like this (not tested):

    global $post;
    $trim_length = 150;  //desired length of text to display
    $summary_excerpt = 'Summary';
    $value = get_post_meta($post->ID, $summary_excerpt, true);
    if ($value != '') {
      if(strlen($value) <= $trim_length){
        echo apply_filters('the_content', $value);
      } else {
        echo apply_filters('the_content', rtrim(substr($value,0,$trim_length)).'...');
      }
    }

    Thread Starter Rose

    (@eos-rose)

    It worked! Thank you!

    Moderator keesiemeijer

    (@keesiemeijer)

    No problem. Glad you got it resolved.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Limit characters in a custom field’ is closed to new replies.