set_post_type()
云策文档标注
概述
set_post_type() 函数用于更新指定文章 ID 的文章类型,并清理相关缓存。它接受文章 ID 和文章类型作为参数,返回受影响的行数以指示操作成功与否。
关键要点
- 函数用于修改文章类型,支持标准类型如 'post' 或 'page',也适用于自定义文章类型。
- 操作后会自动调用 clean_post_cache() 清理文章缓存,确保数据一致性。
- 返回值:成功时返回 1(表示一行被更新),失败时返回 0 或 false。
- 参数 $post_id 和 $post_type 均为可选,默认值分别为 0 和 'post'。
- 内部使用 sanitize_post_field() 对文章类型进行清理,并通过 wpdb::update() 更新数据库。
代码示例
$post_id = 15;
if ( set_post_type( $post_id, 'page' ) ) {
printf( __( 'Post #%d is now a Page', 'textdomain' ), $post_id );
} else {
echo __( 'Impossible to transform this post into a page.', 'textdomain' );
}注意事项
- 函数会保留文章的标题、内容等数据,仅改变文章类型。
- 确保传入有效的文章 ID 和文章类型字符串,以避免操作失败。
- 适用于需要动态调整文章类型的场景,如将文章转换为页面或自定义类型。
原文内容
Updates the post type for the post ID.
Description
The page or post cache will be cleaned for the post ID.
Parameters
$post_idintoptional-
Post ID to change post type. Default 0.
$post_typestringoptional-
Post type. Accepts
'post'or'page'to name a few. Default'post'.
Source
function set_post_type( $post_id = 0, $post_type = 'post' ) {
global $wpdb;
$post_type = sanitize_post_field( 'post_type', $post_type, $post_id, 'db' );
$return = $wpdb->update( $wpdb->posts, array( 'post_type' => $post_type ), array( 'ID' => $post_id ) );
clean_post_cache( $post_id );
return $return;
}
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 3 content
Codex
Example
$post_id = 15; if ( set_post_type( $post_id, 'page' ) ) { printf( __( 'Post #%d is now a Page', 'textdomain' ), $post_id ); } else { echo __( 'Impossible to transform this post into a page.', 'textdomain' ); }Skip to note 4 content
mayur8991
$post_id = 123; //your post id $post_type = 'page'; //your post type name also you can use custom post type if ( set_post_type( $post_id, $post_type ) ) { printf( __( 'Post %d is now a %s', 'textdomain' ), $post_id, $post_type ); } else { printf( __( 'Impossible to transform this post into a %s', 'textdomain' ), $post_type ); }