参数
- $more_link_text
-
(string) (可选) “更多”链接文本
默认值: null
- $strip_teaser
-
(bool) (可选) 删除“更多”文本前面的前导内容
默认值: false
- $post
-
(WP_Post|object|int) (可选) WP_Post实例或Post ID/对象
默认值: null
返回
(string)
说明
当在主循环中使用时,此函数将获取当前文章的内容。
如果在主循环之外使用,则必须使用可选的$post
参数通知要获取内容的文章。
与the_content()
的一个重要区别是get_the_content()
不会将内容通过the_content
过滤器。这意味着get_the_content()
不会自动嵌入视频或扩展短代码等。
源码
更新日志
版本 | 描述 |
---|---|
5.2.0 | 添加了$post 参数 |
0.71 | 开始引入 |
使用示例
请注意,
get_the_content
返回的内容与the_content
显示的内容不同。为此,您需要执行以下操作:$content = apply_filters( 'the_content', get_the_content() ); echo $content;
基本用法,显示文章内容,如果需要,以“阅读更多”结尾
$content = get_the_content( 'Read more' ); echo apply_filters( 'the_content', $content );
找出the_content在输出之前是否有内容
在functions.php中或类似文件:
// write inside the loop $the_content = apply_filters('the_content', get_the_content()); if ( !empty($the_content) ) { echo $the_content; } // with post object by id $post = get_post(12); // specific post $the_content = apply_filters('the_content', $post->post_content); if ( !empty($the_content) ) { echo $the_content; }
作为函数
// call inside the loop or with ID // taken from has_excerpt() // https://developer.wordpress.org/reference/functions/has_excerpt function mytheme_has_content( $post = 0 ){ $post = get_post( $post ); return ( !empty(apply_filters('the_content', $post->post_content)) ); }
循环内的模板:
<?php if ( $customQuery->have_posts() ) {?> <?php while ( $customQuery->have_posts() ) { $customQuery->the_post(); ?> <?php $the_content = apply_filters('the_content', get_the_content()); ?> <!-- html --> <?php if ( !empty($the_content) ) { ?> <div class="content"> <?php echo $the_content; ?> </div> <?php } ?> <?php } ?> <?php wp_reset_postdata(); ?> <?php } ?>
如果在设置全局$wp_query对象之前使用
get_the_content()
,则不会很好地生成postmeta,因为generate_postdata()
使用$wp_query
要解决这个问题,只需在调用get_the_content()
之前构造一个全局$wp_query对象global $wp_query; $wp_query = new WP_Query();