> WordPress中文手册 > WordPress文章函数:is_single()

【说明】

判断一个单独一面是否被显示,返回 TRUE 或者 FALSE

【用法】

<?PHP is_single($post); ?>

【参数】
$post
(mixed) (optional) Post ID, Post Title or Post Slug

默认: None
【返回值】
(boolean)
成功 True, 失败 false.

【示例】

is_single();
// 当任何文章页面被显示.

is_single('17');
// 当文章ID为17的被显示.

is_single(17);
// 当文章ID为17的被显示。 整形的参数也可以。

is_single('Irish Stew');
// 文章的标题为"Irish Stew"的被显示.

is_single('beef-stew');
// 当文章的别名 post_name (slug) 是 "beef-stew" 的 被显示.

is_single(array(17,'beef-stew','Irish Stew'));
// 当文章的 ID是17, 或者别名 post_name 是 "beef-stew",或者文章的标题是"Irish Stew"的返回True.  注意: 数组参数的功能是在 2.5版本添加的.

【注意】
类似功能: is_singular()

【源文件】

is_single() 在 wp-includes/query.php.

/**
 * Is the query for a single post?
 *
 * Works for any post type, except attachments and pages
 *
 * If the $post parameter is specified, this function will additionally
 * check if the query is for one of the Posts specified.
 *
 * @see is_page()
 * @see is_singular()
 *
 * @see WP_Query::is_single()
 * @since 1.5.0
 * @uses $wp_query
 *
 * @param mixed $post Post ID, title, slug, or array of such.
 * @return bool
 */
function is_single( $post = '' ) {
 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' );
  return false;
 }

 return $wp_query->is_single( $post );
}


/**
  * Is the query for a single post?
  *
  * Works for any post type, except attachments and pages
  *
  * If the $post parameter is specified, this function will additionally
  * check if the query is for one of the Posts specified.
  *
  * @see WP_Query::is_page()
  * @see WP_Query::is_singular()
  *
  * @since 3.1.0
  *
  * @param mixed $post Post ID, title, slug, or array of such.
  * @return bool
  */
 function is_single( $post = '' ) {
  if ( !$this->is_single )
   return false;

  if ( empty($post) )
   return true;

  $post_obj = $this->get_queried_object();

  $post = (array) $post;

  if ( in_array( $post_obj->ID, $post ) )
   return true;
  elseif ( in_array( $post_obj->post_title, $post ) )
   return true;
  elseif ( in_array( $post_obj->post_name, $post ) )
   return true;

  return false;
 }