WordPress:get_the_content()和the_content()之间的区别

时间:2018-06-17 00:36:44

标签: php wordpress

我正在研究WordPress中的新主题,并花了大量时间使用get_the_content()函数。

This is line 1
This is line 2
This is line 3
This is line 4

似乎它没有处理快捷方式,也没有段落。

然后我用the_content()替换它;我的段落和快捷方式开始奏效。

  <div class="clearfix">
      <div>
        <p><?=get_the_content();?></p>
      </div>
  </div>

我的问题:函数之间的区别是什么,以及什么是额外处理the_content();与get_the_content();?

进行比较

2 个答案:

答案 0 :(得分:3)

虽然@J Quest提供了足够的答案,但我想详细说明一下。一般来说,WordPress有两种类型的后变量函数:get_函数和the_函数。

get_函数(例如get_the_content()get_the_ID())将返回所需的信息,然后必须将其操作并打印到页面。一些例子:

$content = get_the_content();
$content = apply_filters( 'the_content', $content );
$content = str_replace( 'foo', 'bar', $content );

echo 'Post #'. get_the_ID() . $content;

the_函数,例如the_content()the_ID()实际上echo返回的值,如果适用,将对适当的值应用“默认过滤器”。这些功能不需要回应。

echo get_the_ID();

在功能上与

相同
the_ID();

如果您查看the_ID()的文档,您会看到它只输出get_the_ID()的值。来自消息来源:

function the_ID() {
    echo get_the_ID();
}

在这种情况下,如果您尝试将the_函数设置为变量,您将在整个页面中留下回显变量的踪迹。

$id = the_ID();
echo 'Post ID: $id';

将输出:

123Post ID: 123

要使用get_the_content()并运行短代码,您需要通过do_shortcode()函数或更好的the_content过滤器运行它。

$content = get_the_content();

echo do_shortcode( $content );
// Or:    
echo apply_filters( 'the_content', $content );

如果您只是需要在模板中吐出帖子内容而不进行任何操作,通常情况下会更好(没有回声或回声短标记):

the_content();

答案 1 :(得分:1)

get_the_content()未通过the_content传递内容。这意味着它不会自动嵌入视频,或扩展短代码等。

只需使用get_the_content()即可删除这些标记。

https://codex.wordpress.org/Function_Reference/get_the_content https://developer.wordpress.org/reference/functions/the_content/