unstick_post()
云策文档标注
概述
unstick_post() 函数用于将文章从置顶列表中移除,确保置顶文章在首页顶部显示的逻辑正确性。
关键要点
- 函数接受一个整数类型的文章 ID 作为必需参数。
- 通过 get_option('sticky_posts') 获取当前置顶文章列表,并进行数组处理和唯一性验证。
- 如果文章 ID 不在置顶列表中,函数直接返回;否则,从数组中移除该 ID 并更新选项。
- 更新成功后,会触发 post_unstuck 动作钩子,允许开发者执行自定义操作。
代码示例
function unstick_post( $post_id ) {
$post_id = (int) $post_id;
$stickies = get_option( 'sticky_posts' );
if ( ! is_array( $stickies ) ) {
return;
}
$stickies = array_values( array_unique( array_map( 'intval', $stickies ) ) );
if ( ! in_array( $post_id, $stickies, true ) ) {
return;
}
$offset = array_search( $post_id, $stickies, true );
if ( false === $offset ) {
return;
}
array_splice( $stickies, $offset, 1 );
$updated = update_option( 'sticky_posts', $stickies );
if ( $updated ) {
do_action( 'post_unstuck', $post_id );
}
}注意事项
- 函数内部对 sticky_posts 选项进行数组处理,确保数据一致性,避免重复或非整数 ID。
- post_unstuck 钩子在文章成功移除后触发,可用于日志记录或清理相关缓存。
- 该函数自 WordPress 2.7.0 版本引入,广泛应用于 REST API、XML-RPC 和后台编辑等场景。
原文内容
Un-sticks a post.
Description
Sticky posts should be displayed at the top of the front page.
Parameters
$post_idintrequired-
Post ID.
Source
function unstick_post( $post_id ) {
$post_id = (int) $post_id;
$stickies = get_option( 'sticky_posts' );
if ( ! is_array( $stickies ) ) {
return;
}
$stickies = array_values( array_unique( array_map( 'intval', $stickies ) ) );
if ( ! in_array( $post_id, $stickies, true ) ) {
return;
}
$offset = array_search( $post_id, $stickies, true );
if ( false === $offset ) {
return;
}
array_splice( $stickies, $offset, 1 );
$updated = update_option( 'sticky_posts', $stickies );
if ( $updated ) {
/**
* Fires once a post has been removed from the sticky list.
*
* @since 4.6.0
*
* @param int $post_id ID of the post that was unstuck.
*/
do_action( 'post_unstuck', $post_id );
}
}
Hooks
- do_action( ‘post_unstuck’, int $post_id )
-
Fires once a post has been removed from the sticky list.
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |