函数文档

stick_post()

💡 云策文档标注

概述

stick_post() 函数用于将指定文章设置为置顶,使其在网站首页顶部显示。该函数通过更新 sticky_posts 选项来实现置顶功能,并在成功时触发 post_stuck 钩子。

关键要点

  • 函数接受一个必需的整数参数 $post_id,表示要置顶的文章 ID。
  • 内部逻辑包括获取现有置顶文章数组,检查并添加新文章 ID,避免重复。
  • 成功更新 sticky_posts 选项后,会触发 post_stuck 钩子,允许开发者执行自定义操作。
  • 函数依赖于 get_option()、update_option() 和 do_action() 等核心 WordPress 函数。

代码示例

$post_id = 1;
stick_post( $post_id );

注意事项

  • 确保传入的 $post_id 是有效的整数,否则可能导致错误。
  • 置顶文章列表存储在 sticky_posts 选项中,可通过 get_option('sticky_posts') 获取。
  • 函数在 WordPress 2.7.0 版本中引入,兼容后续版本。

📄 原文内容

Makes a post sticky.

Description

Sticky posts should be displayed at the top of the front page.

Parameters

$post_idintrequired
Post ID.

Source

function stick_post( $post_id ) {
	$post_id  = (int) $post_id;
	$stickies = get_option( 'sticky_posts' );
	$updated  = false;

	if ( ! is_array( $stickies ) ) {
		$stickies = array();
	} else {
		$stickies = array_unique( array_map( 'intval', $stickies ) );
	}

	if ( ! in_array( $post_id, $stickies, true ) ) {
		$stickies[] = $post_id;
		$updated    = update_option( 'sticky_posts', array_values( $stickies ) );
	}

	if ( $updated ) {
		/**
		 * Fires once a post has been added to the sticky list.
		 *
		 * @since 4.6.0
		 *
		 * @param int $post_id ID of the post that was stuck.
		 */
		do_action( 'post_stuck', $post_id );
	}
}

Hooks

do_action( ‘post_stuck’, int $post_id )

Fires once a post has been added to the sticky list.

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes