2

I want to know how I can change the structure of the permalink to my desired one before saving or publishing my post in Wordpress?
For instance, when I add the title like the wordpress blog in my post I get the permalink structure similar to the below:

http://localhost/2015/09/10/the-wordpress-blog/

I want to change it to something like below before saving or publishing it:

http://localhost/2015/09/10/the-wordpress-blog-is-mine/

But I don't know hook what into what to achieve my goal.

1

Finally, I found my answer on my own.

//add our action
add_action( 'save_post', 'my_save_post', 11, 2 );

function my_save_post($post_id, $post){

   //if it is just a revision don't worry about it
   if (wp_is_post_revision($post_id))
      return false;

   //if the post is an auto-draft we don't want to do anything either
   if($post->post_status != 'auto-draft' ){

       // unhook this function so it doesn't loop infinitely
       remove_action('save_post', 'my_save_post' );

      //this is where it happens -- update the post and change the post_name/slug to the post_title
      wp_update_post(array('ID' => $post_id, 'post_name' => str_replace(' ', '-', $_POST['post_title'])));

      //re-hook this function
      add_action('save_post', 'my_save_post' );
   }
}
  • This function looks like it is doing what WordPress already does when it auto-generates the slug based on the title; simply replacing the " " with "-". The only thing the WordPress one does is run it through strtolower(). – Cedon Sep 10 '15 at 20:32
  • @belinus The answer you gave is really superfluous since it is addressing something which is obvious. The function above can be improved a little bit to work as I intend. – FreeMind Sep 11 '15 at 10:51
0

Underneath the Title field is the slug field. Normally WordPress will automatically create a slug base on what you are typing in the Title field. All you need to do is type in what you want that to be and then publish.

  • I am aware of the slug field in the post page of the Wordpress, I am looking for a way to filter the slug after the post is saved. I want to programmatically modify the slug to my own desired format. – FreeMind Sep 10 '15 at 18:18
  • 1
    What exactly do you want to do with the structure then? Because in your examples, you merely change the content. – Cedon Sep 10 '15 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.