Support » Developing with WordPress » how to add … if string length is more than 50?

  • I would like to stop my testimonial_text form going over 50 chars and then add … at the end.

    <?php the_sub_field('testimonial_text', 5);?>

    I have tried the following that didn’t work:

    <?php
    $string = the_sub_field('testimonial_text', 5);
    
    if( strlen( $string ) > 50 ) {
       $string = substr( $string, 0, 50 ) . '...';
    }
    
    echo $string
    • This topic was modified 3 years, 7 months ago by jmbiddulph.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Dion

    (@diondesigns)

    The the_sub_field() function is not part of WordPress. You’ll need to address your question to the authors who wrote the function.

    Having said this, it’s kinda obvious the function echoes the string. What you need is a get_the_sub_field() function, which may or may not exist.

    Also keep in mind that the PHP strlen() and substr() functions are not multibyte-safe, so if your text contains non-ASCII UTF-8 characters, your code will not work correctly. If your PHP installation has the mbstring extension installed, you should instead use the mb_strlen() and mb_substr() functions.

    Moderator bcworkz

    (@bcworkz)

    If there is no get_the_sub_field(), there is a possibility there is a filter within the_sub_field() or one of the functions that it calls which you could use. Some functions like this will let us pass a parameter when calling the function that will cause it to return a value instead of echoing. As Dion suggests, seek guidance from those who wrote the function.

    Failing that, you may need to get the data through other means. There’s a good chance the data is in post meta and you could get the data with get_post_meta(). The meta key may not be ‘testimonial_text’, so further investigation is warranted if you go this route.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘how to add … if string length is more than 50?’ is closed to new replies.