Search code examples
wordpresscustom-post-typepermalinks

Dynamic permalinks when creating a post in WordPress


I have a custom post type named houses. Inside my custom post type I have several custom fields which I created using ACF.

What I need to do is to change the permalink when I create a new post.

I would like to use the code and title fields to customize the permalink:

//code + post title
4563312-house-example-1

I'm developing a plugin which controls everything.

Is there a way to intermediate the creation of a post to update its permalink?

Thanks.


Solution

  • After some research, I found an answer related to wp_insert_post_data.

    Using wp_insert_post_data, I couldn't get the custom field value, and to achieve that, I had to use another action, save_post instead.

    function rci_custom_permalink($post_id) {
      $post = get_post($post_id);
      if($post->post_type !== 'houses') return;
    
      $code = get_field('code', $post_id);
      $post_name = sanitize_title($post->post_title);
      $permalink = $code . '-' . $post_name;
    
      // remove the action to not enter in a loop
      remove_action('save_post', 'rci_custom_permalink');
    
      // perform the update
      wp_update_post(array('ID' => $post_id, 'post_name' => $permalink));
    
      // add the action again
      add_action('save_post', 'rci_custom_permalink');
    } 
    
    add_action('save_post', 'rci_custom_permalink');
    

    PS: Since all these fields are required, I didn't need to check if they are empty or not.

    For reference about save_post action: Plugin API/Action Reference/save post