函数文档

has_post_format()

💡 云策文档标注

概述

has_post_format() 函数用于检查文章是否具有指定的文章格式或任何格式。它基于 has_term() 实现,通过 sanitize_key() 处理格式参数。

关键要点

  • 检查文章是否具有给定格式或任何格式,返回布尔值
  • 参数 $format 可选,可以是字符串或字符串数组,默认空数组
  • 参数 $post 可选,指定要检查的文章,默认为当前循环中的文章
  • 内部将格式转换为 'post-format-' 前缀的术语,并调用 has_term() 进行验证
  • 自 WordPress 3.1.0 版本引入

代码示例

$format = has_post_format($format, $post_id);

注意事项

  • 使用 sanitize_key() 确保格式参数安全
  • 相关函数:has_term() 用于检查术语,sanitize_key() 用于字符串键的清理

📄 原文内容

Check if a post has any of the given formats, or any format.

Parameters

$formatstring|string[]optional
The format or formats to check.

Default:array()

$postWP_Post|int|nulloptional
The post to check. Defaults to the current post in the loop.

Default:null

Return

bool True if the post has any of the given formats (or any format, if no format specified), false otherwise.

More Information

Usage:
$format = has_post_format($format, $post_id);

Source

function has_post_format( $format = array(), $post = null ) {
	$prefixed = array();

	if ( $format ) {
		foreach ( (array) $format as $single ) {
			$prefixed[] = 'post-format-' . sanitize_key( $single );
		}
	}

	return has_term( $prefixed, 'post_format', $post );
}

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes