Using WordPress ‘get_post_format_slugs()’ PHP function

The get_post_format_slugs() WordPress PHP function retrieves the array of post format slugs.

Usage

To use the function, simply call it without any parameters. For example:

$post_format_slugs = get_post_format_slugs();

Parameters

  • None

More information

See WordPress Developer Resources: get_post_format_slugs

Examples

Display All Post Format Slugs

This code will retrieve and display all post format slugs.

// Get all post format slugs
$post_format_slugs = get_post_format_slugs();

// Loop through the post format slugs and display them
foreach ($post_format_slugs as $slug) {
    echo 'Post Format Slug: ' . $slug . '<br>';
}

Show Post Format Name from Slug

This code will retrieve the post format name from a given slug.

function get_post_format_name_from_slug($slug) {
    // Get all post format slugs
    $post_format_slugs = get_post_format_slugs();

    // Return the post format name if the slug exists
    return array_search($slug, $post_format_slugs);
}

// Usage
$slug = 'post-format-gallery';
$post_format_name = get_post_format_name_from_slug($slug);
echo 'Post Format Name: ' . $post_format_name;

Filter Posts by Post Format Slug

This code filters and displays posts with a specific post format slug.

// Get posts with a specific post format slug
$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'post_format',
            'field' => 'slug',
            'terms' => 'post-format-gallery'
        )
    )
);
$query = new WP_Query($args);

// Display the post titles
while ($query->have_posts()) {
    $query->the_post();
    echo '<h2>' . get_the_title() . '</h2>';
}

Convert Post Format Slugs to Names

This code will convert an array of post format slugs to their corresponding names.

function convert_slugs_to_names($slugs) {
    // Get all post format slugs
    $post_format_slugs = get_post_format_slugs();

    // Convert slugs to names
    $names = array();
    foreach ($slugs as $slug) {
        $names[] = array_search($slug, $post_format_slugs);
    }

    return $names;
}

// Usage
$post_format_slugs = array('post-format-gallery', 'post-format-video');
$post_format_names = convert_slugs_to_names($post_format_slugs);
print_r($post_format_names);

Check if Post Format Slug Exists

This code checks if a post format slug exists and returns a boolean value.

function is_post_format_slug_exists($slug) {
    // Get all post format slugs
    $post_format_slugs = get_post_format_slugs();

    // Check if the given slug exists
    return in_array($slug, $post_format_slugs);
}

// Usage
$slug = 'post-format-gallery';
$result = is_post_format_slug_exists($slug);
echo $slug . ' exists: ' . ($result ? 'Yes' : 'No');