I am trying to: Use two custom fields as a dashed string for CPT Title & Slug. I referenced this post: https://toolset.com/forums/topic/use-custom-fields-to-set-post-title-and-post-slug/ to assist me in getting the function going. I have a CPT with a slug of 'bulletins'. Thus my problematic code snippet in use at present is:
add_filter( 'wp_insert_post_data' , 'set_bulletins_title' , '10', 2 );
function set_bulletins_title( $data , $postarr ) {
if ( 'bulletins' != $data['post_type'] )
return $data;
$post_title = $data['post_title'];
if ( ! $post_title ) {
$bulletins_year = trim( $_POST['wpcf']['year-of-bulletin-release']);
$bulletins_number = trim( $_POST['wpcf']['special-bulletin-number']);
$bulletins_title = $bulletins_year . ' - ' . $bulletins_number;
$post_slug = sanitize_title_with_dashes ($bulletins_title,'','save');
$post_slugsan = sanitize_title($post_slug);
$data['post_title'] = $bulletins_title;
$data['post_name'] = $post_slugsan;
}
return $data;
}
Link to a page where the issue can be seen:
I expected to see: I thought I would see each new post titled (complete with corresponding slug) with the Year & the Bulletin Number with a Dash separating these two wpcf
Instead, I got: Auto Draft in the title & auto-draft-x in the slug.
Technically this is custom code we cannot support because it does not use any of Toolset's APIs.
We can support such similar code quests if it uses Toolset Forms, for example.
Also, using Gutenberg you won't be able to save a post if no title is inserted. You'd hence need to use the classic editor.
In this case the code indeed works.
add_filter( 'wp_insert_post_data' , 'set_issue_title' , '10', 3 );
function set_issue_title( $data , $postarr ) {
if ( 'my_post_type' != $data['post_type'] )
return $data;
$post_title = $data['post_title'];
if ( ! $post_title ) {
$issue_number = trim( $_POST['wpcf']['single1'] );
$issue_type = trim( $_POST['wpcf']['single2']);
$issue_title = $issue_type . ' - ' . $issue_number;
$post_slug = sanitize_title_with_dashes ($issue_title,'','save');
$post_slugsan = sanitize_title($post_slug);
$data['post_title'] = $issue_title;
$data['post_name'] = $post_slugsan;
}
return $data;
}
I use a custom post type with slug my_post_type and 2 Fields with each a slug of single1 and single2
If you still do not get any results you'd have to debug the code and find out what your bulletins_title variable outputs in the process, as likely it's empty.
Or, you can try to fire the hook later (at around 30) because often Custom data of Types is ready only after 20, you can see more about this here:
https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/#snippet-execution-timing
My issue is resolved now. Thank you!