函数文档

is_preview()

💡 云策文档标注

概述

is_preview() 是一个 WordPress 条件标签函数,用于判断当前查询是否为文章或页面的预览状态。它基于全局 $wp_query 对象,返回布尔值。

关键要点

  • 函数返回 bool 类型,表示查询是否为预览。
  • 在查询运行前调用会触发 _doing_it_wrong() 警告并返回 false。
  • 不检查用户登录状态或编辑权限,仅基于 URL 参数(如 ?preview=true)判断。
  • 常用于主题开发中控制预览时的特定行为,如隐藏评论或分析代码。

代码示例

if ( ! is_preview() ) {
    // 在非预览时包含分析代码
}

注意事项

  • 使用 current_user_can() 来检查用户角色和能力,而非依赖 is_preview() 进行权限验证。
  • 在预览中可结合其他条件标签(如 is_single())优化功能逻辑。

📄 原文内容

Determines whether the query is for a post or page preview.

Description

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

Return

bool Whether the query is for a post or page preview.

Source

function is_preview() {
	global $wp_query;

	if ( ! isset( $wp_query ) ) {
		_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
		return false;
	}

	return $wp_query->is_preview();
}

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    function comments_template( $file = '/comments.php', $separate_comments = false ) {
    global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage;
    
    if ( ! ( is_single() || is_page() || $withcomments ) || empty( $post ) ) {
    return;
    }
    
    if ( is_preview() ) {
    return;
    }

    Useful to stop comments showing in the preview, especially if you use Disqus Conditional Load. This made the preview work for me, as DCL stopped them from working. Add this to wp-includes/comment-template.php.