Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Template Parts: Avoid duplicate titles on creation #46996

Merged
merged 1 commit into from
Jan 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { plus } from '@wordpress/icons';
import { useHistory } from '../routes';
import { store as editSiteStore } from '../../store';
import CreateTemplatePartModal from '../create-template-part-modal';
import { useExistingTemplateParts } from './utils';

export default function NewTemplatePart( {
postType,
Expand All @@ -31,6 +32,7 @@ export default function NewTemplatePart( {
const { createErrorNotice } = useDispatch( noticesStore );
const { saveEntityRecord } = useDispatch( coreStore );
const { __unstableSetCanvasMode } = useDispatch( editSiteStore );
const existingTemplateParts = useExistingTemplateParts();

async function createTemplatePart( { title, area } ) {
if ( ! title ) {
Expand All @@ -40,6 +42,26 @@ export default function NewTemplatePart( {
return;
}

const uniqueTitle = () => {
const lowercaseTitle = title.toLowerCase();
const existingTitles = existingTemplateParts.map(
( templatePart ) => templatePart.title.rendered.toLowerCase()
);

if ( ! existingTitles.includes( lowercaseTitle ) ) {
return title;
}

let suffix = 2;
while (
existingTitles.includes( `${ lowercaseTitle } ${ suffix }` )
) {
suffix++;
}

return `${ title } ${ suffix }`;
};

try {
// Currently template parts only allow latin chars.
// Fallback slug will receive suffix by default.
Expand All @@ -52,7 +74,7 @@ export default function NewTemplatePart( {
'wp_template_part',
{
slug: cleanSlug,
title,
title: uniqueTitle(),
content: '',
area,
},
Expand Down
14 changes: 14 additions & 0 deletions packages/edit-site/src/components/add-new-template/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ export const useExistingTemplates = () => {
);
};

export const useExistingTemplateParts = () => {
return useSelect(
( select ) =>
select( coreStore ).getEntityRecords(
'postType',
'wp_template_part',
{
per_page: -1,
}
),
[]
);
};

export const useDefaultTemplateTypes = () => {
return useSelect(
( select ) =>
Expand Down