wp_trim_words除了普通字符串之外什么都不起作用

时间:2012-06-26 11:25:04

标签: trim custom-fields texttrimming

我在这里有点偏离我的领域,我对此感到困惑。除常规字符串外,使用wp_trim_field不起作用。

这不起作用,它返回整个文本:

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

然而这确实有效:

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

回显$ field而不是回显我试图修剪的文本,但修剪不起作用。关于为什么的任何想法?

编辑 - 我也试过这个,同样的事情发生了:

<?php
   $length = 1;
   $text = the_field('project_description');
   $words = explode(' ', $text);
   array_splice($words, $length);
   $text = implode(' ', $words);
   echo $text; 
?>

2 个答案:

答案 0 :(得分:1)

使用var_dump($field); wp_trim_words( $field,....) $field必须是字符串类型...检查是否要测试数据类型,如果它不确定您知道该怎么做。< / p>

如果不是,请使用typecast

答案 1 :(得分: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/