Rewrite post_name (slug) before publishing a post
-
I have a tough question for you guys… well it’s tough for me, it is probably easy for you.
I am trying to modify a plugin to put the year+title as the post_name. As I go though and manually post the old results, I would like to have the URL read like this: https://www.striders.net/race-results/2012-resolution-run-8k-prediction-run The plugin code does work, but I have to click Update twice. The first time I click Update it always sets the year as 2016 (the current year). The second time I click Update it will pull the ‘publish-on’ date and for example will set the year to 2012 if I set the publish-on date to 2012. Why does $thePost->post_date not have the correct value of 2012 the first time I click Update? Why it does $thePost->post_date have the correct value of 2012 the second time through? Is there a different method other than save_post that I should be hooking or a different date value that I can pull? It seems like the date on the post is automatically set to the current year, and then after the save the date is then updated to 2012.
The reason I am doing this is because I am posting a bunch of old race results and would like to have the dates appear in the past.
Here is the plugin code:
<?php add_action( 'save_post', 'rewrite_post_name' ); function rewrite_post_name( $post_id) { if ( ! wp_is_post_revision( $post_id ) ) { remove_action( 'save_post', 'rewrite_post_name' ); $thePost = get_post(); if ($thePost->post_type === 'post') { $post_name2 = substr($thePost->post_date, 0, 4) . " " . $thePost->post_title; wp_update_post( array( 'ID' => $post_id, 'post_name' => $post_name2 // Rewrite based on Post Title )); } add_action( 'save_post', 'rewrite_post_name' ); } } ?>
- The topic ‘Rewrite post_name (slug) before publishing a post’ is closed to new replies.