Trim Custom Field Output Length

I stumbled across this while creating a query of Custom Post data, where the content needed to be laid out in columns, and rows of equal height.

Rather than create an additional custom field, or add the excerpt to the Post, I found a way to limit the words shown from the Custom Field.

$trim_length = 100;  //desired length of text to display
$custom_field = 'my-custom-field-name';
$value = get_post_meta(get_the_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;
}

This also works with ACF.

Source.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.