WordPress页面函数: is_page()


【描述】
用于判断当前页面是否被显示.布尔型函数,返回 TRUE 或者 FALSE. 这个方法必须在loop循环前使用,并且 在Loop循环中不能使用.
【使用】

  1. <?php is_page($page); ?>

【参数】

$page
(混合型) (optional) 页面 ID, 页面 Title or 页面 Slug
默认: None
返回值
(boolean)
成功返回true,失败返回 false.

【例子】

  1. is_page();
  2. // 当任何页面被显示.
  3.  
  4. is_page(42);
  5. // 当页面id是42被显示.
  6.  
  7. is_page('Contact');
  8. // 当标题post_title 是 "Contact"的页面被显示.
  9.  
  10. is_page('about-me');
  11. // 当别名post_name (slug) 是 "about-me" 的页面被显示.
  12.  
  13. is_page(array(42,'about-me','Contact'));
  14. // 当 post ID 42, 或者 post_name 是 "about-me", 或者 post_title 是 "Contact". 返回 true 注意: 数组变量在 版本 2.5 添加.

【注意】
传入一下空变量将会返回true

  1. is_page( '' )
  2. is_page( 0 )
  3. is_page( '0' )
  4. is_page( null )
  5. is_page( false )
  6. is_page( array() )■See also: is_singular()

不能在Loop循环内使用
如果在Loop循环后使用必须先调用 wp_reset_query() .

【源文件】
is_page() 位于 wp-includes/query.php.

  1. /**
  2. * Is the query for a single page?
  3. *
  4. * If the $page parameter is specified, this function will additionally
  5. * check if the query is for one of the pages specified.
  6. *
  7. * @see WP_Query::is_single()
  8. * @see WP_Query::is_singular()
  9. *
  10. * @since 3.1.0
  11. *
  12. * @param mixed $page Page ID, title, slug, or array of such.
  13. * @return bool
  14. */
  15. function is_page( $page = '' ) {
  16. if ( !$this->is_page )
  17. return false;
  18.  
  19. if ( empty( $page ) )
  20. return true;
  21.  
  22. $page_obj = $this->get_queried_object();
  23.  
  24. $page = (array) $page;
  25.  
  26. if ( in_array( $page_obj->ID, $page ) )
  27. return true;
  28. elseif ( in_array( $page_obj->post_title, $page ) )
  29. return true;
  30. else if ( in_array( $page_obj->post_name, $page ) )
  31. return true;
  32.  
  33. return false;
  34. }