Forums

How to character limit for custom fields? (7 posts)

  1. turkishjapan
    Member
    Posted 2 years ago #

    Hi all.

    I wanna show a custom field value but it need a character limit.

    For example:

    value in custom fields: Lorem Ipsum is simply dummy text of the printing and typesetting industry.

    I want to use: Lorem Ipsum is simply...

  2. MichaelH
    Volunteer
    Posted 2 years ago #

    <?php
    $trim_length = 21;  //desired length of text to display
    $custom_field = 'your custom field key here';
    $value = get_post_meta($post->ID, $custom_field, true);
    if ($value) {
      echo '<p>I want to use: ' . rtrim(substr($value,0,$trim_length)) . '...</p>';
    }
    ?>
  3. fcarthy
    Member
    Posted 1 year ago #

    Hi MichaelH,

    I can't seem the get this to work. When I put this in my functions.php file I got an error due to the <?php that's at the beginning. I placed the code exactly like this to not get an error:

    $trim_length = 21;  //desired length of text to display
    $custom_field = 'your custom field key here';
    $value = get_post_meta($post->ID, $custom_field, true);
    if ($value) {
      echo '<p>I want to use: ' . rtrim(substr($value,0,$trim_length)) . '...</p>';
    }

    but it still doesn't work.. why am I doing wrong?

  4. fcarthy
    Member
    Posted 1 year ago #

    Correction, this is how I placed my code:

    $trim_length = 21;  //desired length of text to display
    $custom_field = 'drink description';
    $value = get_post_meta($post->ID, $custom_field, true);
    if ($value) {
      echo '<p>I want to use: ' . rtrim(substr($value,0,$trim_length)) . '...</p>';
    }
  5. fcarthy
    Member
    Posted 1 year ago #

    any help is welcome!

  6. fcarthy
    Member
    Posted 1 year ago #

    I placed the code in my loop so that it pulls the custom field on every post like so:

    <?php
    		$trim_length = 5;  //desired length of text to display
    		$custom_field = 'drink description';
    		$value = get_post_meta($post->ID, $custom_field, true);
    		if ($value) {
    		  echo rtrim(substr($value,0,$trim_length));
    		}
    		?>

    but no dice....

  7. fcarthy
    Member
    Posted 1 year ago #

    got it to work. It was working this last time I tried, i just hadn't noticed it... thanks for the code!

Topic Closed

This topic has been closed to new replies.

About this Topic