函数文档

has_excerpt()

💡 云策文档标注

概述

has_excerpt() 是 WordPress 的一个条件函数,用于判断文章是否设置了自定义摘要。它检查 post_excerpt 字段是否非空,返回布尔值。

关键要点

  • 函数用途:判断文章是否有自定义摘要,常用于主题开发中的条件逻辑。
  • 参数:可选 $post(整数或 WP_Post 对象),默认使用全局 $post。
  • 返回值:布尔值,true 表示有自定义摘要,false 表示无。
  • 内部实现:基于 get_post() 获取文章数据,检查 post_excerpt 字段。
  • 版本历史:自 WordPress 2.3.0 引入。

代码示例

// 示例1:隐藏自动摘要,仅显示自定义摘要
if ( ! has_excerpt() ) {
    echo '';
} else { 
    the_excerpt();
}

// 示例2:测试文章是否有摘要
global $post;
if ( has_excerpt( $post->ID ) ) {
    // 此文章有摘要
} else {
    // 此文章无摘要
}

// 示例3:无摘要时显示内容前200字符
if ( has_excerpt() ) {
    the_excerpt();
} else { 
    echo substr( get_the_content(), 0, 200 ) . ' ' . __( 'read more..' );
}

注意事项

  • 函数依赖于 get_post() 获取文章数据,确保参数有效或全局 $post 已设置。
  • 在函数内部使用时应通过参数或全局变量传递文章信息。
  • 适用于主题开发,更多信息可参考 Theme Developer Handbook 中的 Conditional Tags 文章。

📄 原文内容

Determines whether the post has a custom excerpt.

Description

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.

Parameters

$postint|WP_Postoptional
Post ID or WP_Post object. Default is global $post.

Return

bool True if the post has a custom excerpt, false otherwise.

Source

function has_excerpt( $post = 0 ) {
	$post = get_post( $post );
	return ( ! empty( $post->post_excerpt ) );
}

Changelog

Version Description
2.3.0 Introduced.

User Contributed Notes