Duplicate Post Name In WordPress
In WordPress 2.8.4, from the function wp_unique_post_slug in line 1730 in wp-include/post.php, we can see that the post_name is not allowed to be duplicated.
Given the desired slug and some post details computes a unique slug for the post.
For instance,(the idea comes from perfectlyclear)
2008/07/dress-of-the-day.html is a page that exists and is viewable on the site
but if I try to add a new post of the same title (note the different dates)
2009/08/dress-of-the-day.html the moment you hit “update post” the URL would changes to2009/06/dress-of-the-day-1.html
and if you have lots of posts entitled dress-of-the-day.html, then the increments keep getting larger i.e. -2 -3 etc.
So to achieve our goal, we have to trim the suffix before it is written to the database while updating or adding a post with a duplicated name.
In this case, I’d like to introduce you the conception of filter in WordPress.
Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages), and between the browser and the database (when WordPress is adding new posts and comments to the database); most input and output in WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin can add its own filtering.
Please see further explanation in the following short code.
1 2 3 4 5 6 7 8 9 10 11 | <?php add_filter( 'wp_insert_post_data' , 'wh_duplicat_post_name' , '99' ); function wh_duplicate_post_name( $data) { $wh_post_name=$data['post_name']; if(substr($wh_post_name, -2)=="-2") $data['post_name']=substr($wh_post_name, 0, -2); return $data; } ?> |
To get the code executed, you just simply add it the function.php file in your current theme root directory.
Hopefully it works for you!