1
votes

I have a custom post named session where there are some custom fields such as date, and event_location.

I want to generate a title for this custom post, with the following code :

add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );

function modify_post_title( $data , $postarr )
{
  if($data['post_type'] == 'session') {

  //the id of the post
  $post_id = $postarr['ID'];

  //the date
  $date = get_post_meta( $post_id, 'session_date', true );

  //the location
  $event_location = get_post_meta( $post_id, 'session_location', true );

  //concatenating location and date
  $data['post_title'] = "$event_location-$date";
  }

  //returning the data
  return $data;
}

In order to make it work, i.e. in order to have a properly "forged" title used as a permalink (such as www.mysite.com/session/toronto-04282016), here is what I must do :

  • create a new session and fill the required custom fields
  • save it as a draft
  • reload the page where the session was edited
  • publish the session post

If I try to publish directly the custom post, its permalink takes the #id of the post such as : www.mysite.com/session/432.

EDIT : and the custom post title is empty

EDIT #2 : in the admin panel, if I click on update for a "directly published" custom post, its permalink and title take the "correct" form.

How can I do to be able to publish a new session with a custom title without using the draft step ?

Maybe the filter is not called when a custom post "session" is published. How can I force it to be called ?

1

1 Answers

0
votes

You can change the permalink inside wp_insert_post_data using the post_name parameter (which is the page slug) like this (the following use the sanitize_title function to generate a valid permalink from post title):

$data['post_name'] = sanitize_title($data['post_title']);