Skip to content

Commit 81c215d

Browse files
committed
Update Post Slug while Draft on Title Changes
Closes #5062 * As long as the post has never been published, update the slug to match the new title if the title is changed
1 parent ef0945b commit 81c215d

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

core/server/models/post.js

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,13 @@ Post = ghostBookshelf.Model.extend({
9494
var self = this,
9595
tagsToCheck,
9696
title,
97-
i;
97+
i,
98+
// Variables to make the slug checking more readable
99+
newTitle = this.get('title'),
100+
prevTitle = this._previousAttributes.title,
101+
prevSlug = this._previousAttributes.slug,
102+
postStatus = this.get('status'),
103+
publishedAt = this.get('published_at');
98104

99105
options = options || {};
100106
// keep tags for 'saved' event and deduplicate upper/lowercase tags
@@ -139,13 +145,31 @@ Post = ghostBookshelf.Model.extend({
139145
}
140146
}
141147

142-
if (this.hasChanged('slug') || !this.get('slug')) {
148+
// If a title is set, not the same as the old title, a draft post, and has never been published
149+
if (prevTitle !== undefined && newTitle !== prevTitle && postStatus === 'draft' && !publishedAt) {
143150
// Pass the new slug through the generator to strip illegal characters, detect duplicates
144-
return ghostBookshelf.Model.generateSlug(Post, this.get('slug') || this.get('title'),
151+
return ghostBookshelf.Model.generateSlug(Post, this.get('title'),
145152
{status: 'all', transacting: options.transacting, importing: options.importing})
146153
.then(function then(slug) {
147-
self.set({slug: slug});
154+
// After the new slug is found, do another generate for the old title to compare it to the old slug
155+
return ghostBookshelf.Model.generateSlug(Post, prevTitle).then(function then(prevTitleSlug) {
156+
// If the old slug is the same as the slug that was generated from the old title
157+
// then set a new slug. If it is not the same, means was set by the user
158+
if (prevTitleSlug === prevSlug) {
159+
self.set({slug: slug});
160+
}
161+
});
148162
});
163+
} else {
164+
// If any of the attributes above were false, set initial slug and check to see if slug was changed by the user
165+
if (this.hasChanged('slug') || !this.get('slug')) {
166+
// Pass the new slug through the generator to strip illegal characters, detect duplicates
167+
return ghostBookshelf.Model.generateSlug(Post, this.get('slug') || this.get('title'),
168+
{status: 'all', transacting: options.transacting, importing: options.importing})
169+
.then(function then(slug) {
170+
self.set({slug: slug});
171+
});
172+
}
149173
}
150174
},
151175

0 commit comments

Comments
 (0)