函数文档

is_sticky()

💡 云策文档标注

概述

is_sticky() 函数用于判断指定文章是否为置顶文章。它通过检查文章 ID 是否在 sticky_posts 选项数组中来实现,并支持过滤器钩子进行自定义。

关键要点

  • 函数返回布尔值,表示文章是否为置顶
  • 参数 $post_id 可选,默认为当前循环中的文章 ID
  • 内部使用 get_option('sticky_posts') 获取置顶文章列表
  • 包含 apply_filters('is_sticky', $is_sticky, $post_id) 钩子,允许过滤结果
  • 与 get_the_ID()、absint() 等函数关联,常用于主题开发

代码示例

is_sticky();
// 当显示任何置顶文章页面时。

is_sticky('17');
// 当显示 ID 为 17 的置顶文章时。

📄 原文内容

Determines whether a post is sticky.

Description

Sticky posts should remain at the top of The Loop. If the post ID is not given, then The Loop ID for the current post will be used.

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

Parameters

$post_idintoptional
Post ID. Default is the ID of the global $post.

Return

bool Whether post is sticky.

Source

function is_sticky( $post_id = 0 ) {
	$post_id = absint( $post_id );

	if ( ! $post_id ) {
		$post_id = get_the_ID();
	}

	$stickies = get_option( 'sticky_posts' );

	if ( is_array( $stickies ) ) {
		$stickies  = array_map( 'intval', $stickies );
		$is_sticky = in_array( $post_id, $stickies, true );
	} else {
		$is_sticky = false;
	}

	/**
	 * Filters whether a post is sticky.
	 *
	 * @since 5.3.0
	 *
	 * @param bool $is_sticky Whether a post is sticky.
	 * @param int  $post_id   Post ID.
	 */
	return apply_filters( 'is_sticky', $is_sticky, $post_id );
}

Hooks

apply_filters( ‘is_sticky’, bool $is_sticky, int $post_id )

Filters whether a post is sticky.

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes