Customize permalink when creating a post

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.

2 Answers
2

This can be done using the wp_insert_post_data hook.

function house_post_slug( $data ) {
    if ( $data['post_type'] == 'houses' ) {
       $permalink = '';

       if ( isset ( $_POST['ACF Code Field'] ) ) {
          $permalink = $_POST['ACF Code Field'];
       }

       if ( isset ( $_POST['post_title'] ) ) {
          $permalink .= '-' . $_POST['post_title'];
       }

       $data['post_name'] = sanitize_title( $permalink )
    }

    error_log( '=== Filter $data ===');
    error_log( print_r($data, true) );
    return $data;

}
add_filter( 'wp_insert_post_data', 'house_post_slug' );

So what this filter will do is intercept $data from WordPress, check to see if the post_type field is for your custom post type so it will only fire for that particular CPT.

Then it will check to see if the ACF Code Field is set. And if it is, then it will set `$permalink to that value.

I have not used ACF so I am not sure what the structure they use is. You can see a dump of this by adding:

error_log( print_r ( $_POST, true ) );

Next, it will check and see if the post_title key is set. If so, then it will append - and whatever the value of post_title is.

Finally, we set the post_name key in $data to a sanitized version of $permalink and then return that.

I put in two error_log() statements so you can see the dump of $data for diagnostic purposes.

Leave a Comment