@@ -94,7 +94,13 @@ Post = ghostBookshelf.Model.extend({
94
94
var self = this ,
95
95
tagsToCheck ,
96
96
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' ) ;
98
104
99
105
options = options || { } ;
100
106
// keep tags for 'saved' event and deduplicate upper/lowercase tags
@@ -139,13 +145,31 @@ Post = ghostBookshelf.Model.extend({
139
145
}
140
146
}
141
147
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 ) {
143
150
// 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' ) ,
145
152
{ status : 'all' , transacting : options . transacting , importing : options . importing } )
146
153
. 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
+ } ) ;
148
162
} ) ;
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
+ }
149
173
}
150
174
} ,
151
175
0 commit comments