0

I´m a bit out of my field here and I´m confused about this. Using wp_trim_field doesn't work for me except for regular strings.

This does not work, it returns the whole text:

<?php 
$field = the_field('project_description');
$trimmedfield = wp_trim_words( $field, $num_words = 1, $more = '… ' );
echo '<p>' . $trimmedfield . '</p>';  
?>

This however does work:

<?php 
$field = 'this text does get trimmed';
$trimmedfield = wp_trim_words( $field, $num_words = 1, $more = '… ' );
echo '<p>' . $trimmedfield . '</p>';  
?>

Echoing out the $field instead does echo out the text that I am trying to trim, but the trimming aint working. Any ideas as to why?

edit - I also tried this, same thing happens:

<?php
   $length = 1;
   $text = the_field('project_description');
   $words = explode(' ', $text);
   array_splice($words, $length);
   $text = implode(' ', $words);
   echo $text; 
?>
Johan Dahl
  • 1,672
  • 3
  • 19
  • 35
  • does your "project_description" field really exists??? – swapnesh Jun 26 '12 at 11:34
  • Yes. If i echo out $field, I get the content of that field. – Johan Dahl Jun 26 '12 at 11:45
  • use var_dump($field); wp_trim_words( $field,....) $field must be string type ...check if this is or not to test the datatype, if its not im sure you know what to do then...and let me know if its solved or not – swapnesh Jun 26 '12 at 11:49
  • var_dump($field) = NULL. Er...I think I found the source of the problem. The field value does not get saved at all in $field, it just get´s outputted right there. Is there a typo I´m missing? – Johan Dahl Jun 26 '12 at 12:05
  • you can typecast the output as string ..pasted my comments as an anwer :) – swapnesh Jun 26 '12 at 12:09

2 Answers2

1

use var_dump($field); wp_trim_words( $field,....) $field must be string type ...check if this is or not to test the datatype, if its not im sure you know what to do then.

Use typecast if its not.

swapnesh
  • 26,318
  • 22
  • 94
  • 126
  • I solved this and it was just a stupid mistake on my part. I was using Advanced Custom Fields for Wordpress and used 'the_field' instead of 'get_field' to get my value. – Johan Dahl Jun 27 '12 at 11:33
1

You'll need to change the $field variable to this: $field = get_field('project_description');

the_field(); outputs the content, while get_field(); retrieves it. In order to pass it through a function, you'll need to retrieve it.

ACF documentation page that answers this question: https://www.advancedcustomfields.com/resources/displaying-custom-field-values-in-your-theme/

jennsuzhoy
  • 61
  • 1
  • 3