I have a custom post type with the following permalink structure
/%match_season%/%match_team%/%postname%-%year%-%monthnum%-%day%/
%match_season% and %match_team% are taxonomies.
The post type contains upcoming fixtures and past fixtures, with the post title set as the opposition name, giving me a nice url structure. However as the team names are the same each season I'm finding WordPress is adding a -2 to the %postname% in the permalink.
I understand the reasons why WordPress adds a number to the end of a permalink, if there is already a page / post with the same slug, but in my case it isn't taking into account the unique date that is also part of the url.
I have tried changing the structure to
/%match_season%/%match_team%/%year%-%monthnum%-%day%-%postname%/
But the same happens.
Is there anyway to avoid this? Any help appreciated.
UPDATE
I have done some further research and came across this post about wp_insert_post_data, which indirectly led me to this post about save_post. So i now have the following function
function change_title( $post_id ) {
// Set variables
$opposition = get_field( 'opposition', $post_id );
$match_date_url = get_the_date( 'Y-m-d', $post_id );
$match_date_title = get_the_date( 'd/m/y', $post_id );
// Build post title and permalink
$post_title = $opposition . ' v Team - ' . $match_date_title;
$post_name = $opposition . ' v Team - ' . $match_date_url;
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post_matches', 'change_title', 10, 3 );
// update the post, which calls save_post again
wp_update_post( array(
'ID' => $post_id,
'post_title' => $post_title,
'post_name' => $post_name,
)
);
// re-hook this function
add_action( 'save_post_matches', 'change_title', 10, 3 );
}
add_action( 'save_post_matches', 'change_title', 10, 3 );
Which is almost what i need.
If it is a new post the custom field isn't added to the title or slug, but the rest is. If the post exists on update the title and slug are updated correctly.
Is there something obvious that I'm missing? Again any help is appreciated.
UPDATE 2
I think i have the solution. As the above code didn't add the ACF custom post type i started to look around that and found acf/save_post
So the code i have now, which seems to work for both new posts and updates to posts is
function create_title( $post_id ) {
// Set variables
$opposition = get_field( 'opposition', $post_id );
$match_date_url = get_the_date( 'Y-m-d', $post_id );
$match_date_title = get_the_date( 'd/m/y', $post_id );
// Set post title and permalink
$post_title = $opposition . ' v Team - ' . $match_date_title;
$post_name = $opposition . ' v Team - ' . $match_date_url;
// update the post, which calls save_post again
wp_update_post( array(
'ID' => $post_id,
'post_title' => $post_title,
'post_name' => $post_name,
)
);
}
add_action( 'acf/save_post', 'create_title', 20 );
Hopefully that helps someone else.