函数文档

get_post_format()

💡 云策文档标注

概述

get_post_format() 函数用于检索文章的格式 slug,通常在循环中调用,也可通过提供文章 ID 在任何地方使用。默认格式(即普通文章)返回 false,但有时被视为 'standard' 格式。

关键要点

  • 参数 $post 可选,可为文章 ID、WP_Post 对象或 null,默认为当前循环中的文章
  • 返回值为字符串(格式 slug)或 false(失败或默认格式)
  • 函数检查文章类型是否支持 post-formats,并获取 post_format 分类法中的术语
  • 当前定义的格式包括:aside、chat、gallery、link、image、quote、status、video、audio
  • 开发者可使用 $format = get_post_format() ? : 'standard'; 来保持一致性处理

代码示例

get_template_part( 'format', get_post_format() );

注意事项

确保有默认的 format.php 文件作为后备模板,模板应命名为 format-link.php、format-aside.php 等格式。


📄 原文内容

Retrieve the format slug for a post

Parameters

$postint|WP_Post|nulloptional
Post ID or post object. Defaults to the current post in the loop.

Default:null

Return

string|false The format if successful. False otherwise.

More Information

This will usually be called in the the loop, but can be used anywhere if a post ID is provided.

The set of currently defined formats are:

  • aside
  • chat
  • gallery
  • link
  • image
  • quote
  • status
  • video
  • audio

Note also that the default format (i.e., a normal post) returns false, but this is also referred in some places as the ‘standard’ format. In some cases, developers may wish to do something like the following to maintain consistency:

$format = get_post_format() ? : 'standard';

Source

function get_post_format( $post = null ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	if ( ! post_type_supports( $post->post_type, 'post-formats' ) ) {
		return false;
	}

	$_format = get_the_terms( $post->ID, 'post_format' );

	if ( empty( $_format ) ) {
		return false;
	}

	$format = reset( $_format );

	return str_replace( 'post-format-', '', $format->slug );
}

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Usage in Templates

    /*
     * Pull in a different sub-template, depending on the Post Format.
     * 
     * Make sure that there is a default format.php file to fall back to as a default.
     * Name templates format-link.php, format-aside.php, etc.
     *
     * You should use this in the loop.
     */
    get_template_part( 'format', get_post_format() );