函数文档

set_post_format()

💡 云策文档标注

概述

set_post_format() 函数用于为文章分配或移除文章格式。它接受文章ID或WP_Post对象和格式字符串作为参数,通过内部处理调用wp_set_post_terms()来设置post_format分类的术语。

关键要点

  • 参数 $post 为必需,可以是整数(文章ID)或WP_Post对象,用于指定目标文章。
  • 参数 $format 为必需字符串,指定要分配的格式;使用空字符串或数组可移除所有格式。
  • 返回值在成功时为受影响术语ID的数组,错误时返回WP_Error,或false。
  • 函数内部会验证文章有效性,并处理格式字符串(如添加'post-format-'前缀或转换为空字符串)。
  • 支持的文章格式列表可参考Post Formats页面,标准格式('standard')会被视为空格式。

代码示例

set_post_format( $post->ID, 'gallery' ); // 将指定文章设置为'gallery'格式

📄 原文内容

Assign a format to a post

Parameters

$postint|WP_Postrequired
The post for which to assign a format.
$formatstringrequired
A format to assign. Use an empty string or array to remove all formats from the post.

Return

array|WP_Error|false Array of affected term IDs on success. WP_Error on error.

More Information

See Post Formats page for supported formats.

Source

function set_post_format( $post, $format ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return new WP_Error( 'invalid_post', __( 'Invalid post.' ) );
	}

	if ( ! empty( $format ) ) {
		$format = sanitize_key( $format );
		if ( 'standard' === $format || ! in_array( $format, get_post_format_slugs(), true ) ) {
			$format = '';
		} else {
			$format = 'post-format-' . $format;
		}
	}

	return wp_set_post_terms( $post->ID, $format, 'post_format' );
}

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes