Skip to main content

Get Post Type Labels

PropertyValue
descriptionGet singular or plural labels for a post type.
tagslib, php, wp, oop
rating

Overview

Get the singular or plural label for a post type. The helper defaults to the current post type, so it works in templates and Bricks loops without passing a post type explicitly.

Supported label types:

  • singular: returns labels like Post, Product, or Event.
  • plural: returns labels like Posts, Products, or Events.

Pass a fallback string when you want a custom value for missing or invalid post types.

Variants

<?php
/**
* Get post type label.
*
* Args:
* post_type -> default = current post type
* type -> singular | plural (default = singular)
* fallback -> optional override
*
* Examples:
* mac_get_post_type_label();
* mac_get_post_type_label( 'product', 'plural' );
*/

if ( ! function_exists( 'mac_get_post_type_label' ) ) {

function mac_get_post_type_label( ?string $post_type = null, string $type = 'singular', string $fallback = '' ): string {

// Resolve post type
if ( $post_type === null || $post_type === '' ) {
$post_type = get_post_type();
}

$type = strtolower( trim( $type ) );
$type = $type === 'plural' ? 'plural' : 'singular';

if ( ! is_string( $post_type ) || $post_type === '' ) {
return $fallback ?: ( 'plural' === $type ? 'Posts' : 'Post' );
}

$post_type = sanitize_key( $post_type );
$obj = get_post_type_object( $post_type );

if ( ! $obj || empty( $obj->labels ) ) {
return $fallback ?: ( 'plural' === $type ? 'Posts' : 'Post' );
}

if ( 'plural' === $type ) {
return $obj->labels->name ?: ( $fallback ?: 'Posts' );
}

return $obj->labels->singular_name ?: ( $fallback ?: 'Post' );
}
}