Skip to content

Commit

Permalink
Enhance accuracy of guessing the default plural label (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
felixarntz authored Sep 11, 2024
1 parent 2957398 commit 3b6bb45
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
12 changes: 11 additions & 1 deletion includes/manager/src/components/cpt-settings-panel.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ import {
import { useEntityProp } from '@wordpress/core-data';
import { POST_TYPE_NAME } from '../constants';

function getPlural( singular ) {
if ( singular.endsWith( 'y' ) ) {
return `${ singular.slice( 0, -1 ) }ies`;
}
if ( singular.endsWith( 's' ) || singular.endsWith( 'ch' ) ) {
return `${ singular }es`;
}
return `${ singular }s`;
}

export const CPTSettingsPanel = function () {
const [ meta, setMeta ] = useEntityProp(
'postType',
Expand All @@ -27,7 +37,7 @@ export const CPTSettingsPanel = function () {
useLayoutEffect( () => {
if ( title !== lastTitle.current ) {
lastTitle.current = title;
setMeta( { ...meta, plural_label: `${ title }s` } );
setMeta( { ...meta, plural_label: getPlural( title ) } );
}
}, [ title, meta, setMeta ] );

Expand Down
18 changes: 17 additions & 1 deletion includes/runtime/class-content-model.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public function __construct( WP_Post $content_model_post ) {
* @return string The plural label.
*/
public function get_plural_label() {
return $this->get_model_meta( 'plural_label' ) ?? "{$this->title}s";
return $this->get_model_meta( 'plural_label' ) ?? $this->get_plural( $this->title );
}

/**
Expand Down Expand Up @@ -143,6 +143,22 @@ private function get_model_meta( $key ) {
return null;
}

/**
* Attempts to get the plural label based on the given singular label.
*
* @param string $singular The singular label.
* @return string The plural label (best guess based on common English grammar rules).
*/
private function get_plural( $singular ) {
if ( str_ends_with( $singular, 'y' ) ) {
return substr( $singular, 0, -1 ) . 'ies';
}
if ( str_ends_with( $singular, 's' ) || str_ends_with( $singular, 'ch' ) ) {
return "{$singular}es";
}
return "{$singular}s";
}

/**
* Registers the custom post type for the content model.
*
Expand Down

0 comments on commit 3b6bb45

Please sign in to comment.