has_post_format()
Check if a post has any of the given formats, or any format.
Uses: has_term()
1 time — 0.001473 sec (very slow) | 50000 times — 63.94 sec (very slow)
No Hooks.
Return
true|false
. True if the post has any of the given formats (or any format, if no format specified), false otherwise.
Usage
has_post_format( $format, $post );
- $format(string|string[])
- The format or formats to check.
Default: array() - $post(WP_Post|int|null)
- The post to check.
Default: current post in the loop
Examples
#1 Demo - check format
Suppose we need to check the format of the post (inside the loop) and display an icon if it is, say, video format:
// inside the loop if( has_post_format( 'video' ) ){ echo "<img src="icon link" alt=""/>"; }
#2 Example of specifying multiple formats to check
Suppose our posts are conventionally divided into news (regular posts) and media (posts with galleries and videos). When outputting in the loop, we need to mark the posts as "media". To do this, we will specify the formats as an array:
if( has_post_format( array('video', 'gallery') ) ){ // this is a media post }
#3 Checking the format of a specific post
This example shows how to check the format of a post with ID = 23:
if( has_post_format( 'status', 23 ) ){ // it's status }
Changelog
Since 3.1.0 | Introduced. |
has_post_format() has post format code WP 6.1.1
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 ); }