WordPress中is_front_page()和is_home()的用法及区别

GD Star Rating
loading...

最近在WordPress论坛里有朋友在反馈zAlive主题 的幻灯片设置有问题,具体表现为设置了幻灯片为只在首页显示,但是在博客页面还是会显示(WordPress可以将首页设置为一个静态页面,用另外一个页面显示博客,详见>>Creating a Static Front Page)。

这就让我想到了is_front_page()is_home(),因为前一段在做主题的时候就查过(囧,当时没认真看),为什么现在还有问题?既然不知道那就再查一下,先来看下两者的官方文档吧。

is_front_page()

描述

This Conditional Tag checks if the main page is a posts or a Page. This is a boolean function, meaning it returns either TRUE or FALSE. It returns TRUE when the main blog page is being displayed and the Settings->Reading->Front page displays is set to “Your latest posts”, or when is set to “A static page” and the “Front Page” value is the current Page being displayed.

调用

<?php is_front_page(); ?>

参数

返回值

(boolean) True on success, false on failure.

is_home()

描述

This Conditional Tag checks if the blog posts index page is being displayed. This is a Boolean function, meaning it returns either TRUE or FALSE.

Note: WordPress 2.1 handles this function differently than prior versions – See static Front Page. If you select a static Page as your frontpage (see is_front_page()), this tag will be applied to your “posts page”.

调用

<?php is_home(); ?>

参数

返回值

(boolean) True on success, false on failure.

is_front_page()和is_home()的区别

从上面两者的定义看is_front_page()is_home()在没有使用静态页作为首页显示的时候,两者都返回true,而在使用静态页作为首页之后则只有is_front_page()返回true。另外is_home()在首页显示里面设置了博客页面(文章页)后,在指定的博客页面(文章页)上返回true。

简而言之,只要是网站首页is_front_page()都会返回true,而is_home()会在博客索引页返回true。

国外也有个帖子在说这两者的区别,他们的结论一样,引用如下:

is_front_page() returns true if the user is on the page or page of posts that is set to the front page on Settings->Reading->Front page displays

So if you set about us as the front page then this conditional will only be true if showing theabout us page.

is_home() return true when on the posts list page, This is usually the page that shows the latest 10 posts.

If the settings under Front page displays are left at default then the home page will return true for both is_front_page() and is_home()

An example of using is_home():

  • You have set your posts page to a page called News.
  • A user navigates there and in the header you want to show additional navigation
  • You could use is_home() to do this.

Chip Bennett(WordPress官方人士)还在该帖下面做了补充:

Exactly. I differentiate as follows: is_front_page() returns true when viewing the Site Front Page (whether displaying the blog posts index or a static page), while is_home() returns true when viewing the Blog Posts Index (whether displayed on the front page or on a static page).

WordPress中is_front_page()和is_home()的用法及区别, 4.5 out of 5 based on 2 ratings

发表评论