函数文档

is_front_page()

💡 云策文档标注

概述

is_front_page() 是 WordPress 的一个条件标签函数,用于判断当前查询是否为网站的前台首页。其行为依赖于“阅读设置”中的“首页显示”选项,当设置为静态页面时,仅在该页面返回 true;否则与 is_home() 相同。

关键要点

  • 用于检测当前查询是否针对网站前台首页,返回布尔值。
  • 依赖于“阅读设置”中的 'show_on_front' 和 'page_on_front' 选项。
  • 如果首页设置为静态页面,则仅在该页面返回 true;否则与 is_home() 行为一致。
  • 在查询运行前调用会返回 false,并触发 _doing_it_wrong() 警告。
  • 相关函数包括 WP_Query::is_front_page()、__() 和 _doing_it_wrong()。
  • 被多个函数如 get_custom_logo()、wp_get_document_title() 等使用。
  • 自 WordPress 2.5.0 版本引入。

代码示例

if ( is_front_page() ) :
    get_header( 'front' );
else :
    get_header();
endif;

注意事项

  • 在查询运行前(如 Action wp 之前)调用此函数可能返回 false,即使后续返回 true。
  • 用户贡献笔记提供了自定义函数示例,用于在特定场景下检查页面是否为首页。

📄 原文内容

Determines whether the query is for the front page of the site.

Description

This is for what is displayed at your site’s main URL.

Depends on the site’s “Front page displays” Reading Settings ‘show_on_front’ and ‘page_on_front’.

If you set a static page for the front page of your site, this function will return true when viewing that page.

Otherwise the same as is_home().

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 the front page of the site.

Source

function is_front_page() {
	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_front_page();
}

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 6 content

    If you are using a static page as your front page, this is useful:

    <title> » </title>

    Usage in a Custom Function

    Added to your themes functions file, this code includes the is_front_page() conditional tag after the function name so the content only displays on the front page.

    add_action( 'loop_start', 'using_front_page_conditional_tag' );
    function using_front_page_conditional_tag() {
    	if ( is_front_page() ) {	
    		echo'<h2>Only Displays On The Front Page</h2>';
    	}
    }

  2. Skip to note 7 content

    To check if any page is the current front page (for example, when you’re in a custom loop) you can use this function. It expects a page ID as argument:

    function wpdocs_page_is_front_page( int $id ) {
        // If this is set to anything else than 'page' there is no front page
        // anyway, so always return false
        if ( 'page' !== get_option( 'show_on_front' ) ) {
            return false;
        }
    
        // Types for option values are string, so convert to int
        $front_id = (int) get_option( 'page_on_front' );
    
        return $front_id == $id;
    }