Using WordPress ‘get_post_format()’ PHP function

The get_post_format() WordPress PHP function retrieves the format slug for a post.

Usage

get_post_format( $post );

Example: If you have a post with the “quote” format, using get_post_format( $post_id ) will return 'quote'.

Parameters

  • $post int|WP_Post|null (Optional) Post ID or post object. Defaults to the current post in the loop. Default: null

More information

See WordPress Developer Resources: get_post_format()

Examples

Display post format for the current post

This example will display the post format for the current post in the loop.

// Display the post format
echo 'Post format: ' . get_post_format();

Check if a post has a specific format

This example checks if the current post has the “video” format.

// Check if the post has a "video" format
if ( 'video' === get_post_format() ) {
    echo 'This is a video post!';
}

Custom output based on post format

This example displays different content based on the post format of the current post in the loop.

// Get the post format
$post_format = get_post_format();

// Display content based on post format
switch ( $post_format ) {
    case 'image':
        echo 'This is an image post.';
        break;
    case 'quote':
        echo 'This is a quote post.';
        break;
    default:
        echo 'This is a standard post.';
}

Use post format in a custom WP_Query loop

This example uses a custom WP_Query loop to display only posts with the “audio” format.

// Set up a custom WP_Query
$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'post_format',
            'field'    => 'slug',
            'terms'    => 'post-format-audio',
        ),
    ),
);
$audio_posts = new WP_Query( $args );

// Loop through audio posts
if ( $audio_posts->have_posts() ) {
    while ( $audio_posts->have_posts() ) {
        $audio_posts->the_post();
        echo '<h2>' . get_the_title() . '</h2>';
    }
    wp_reset_postdata();
}

Retrieve and display all supported post formats

This example retrieves and displays all supported post formats for the active theme.

// Get the supported post formats
$supported_formats = get_theme_support( 'post-formats' );

// Display supported post formats
if ( $supported_formats ) {
    echo 'Supported post formats:';
    echo '<ul>';
    foreach ( $supported_formats[0] as $format ) {
        echo '<li>' . esc_html( $format ) . '</li>';
    }
    echo '</ul>';
}