0

I would like to generate the post title from 2 custom fields, 'job', which is a taxonomy, plus 'date' which is a date picker, not the date of the post. This is for a custom post type called 'job-updates'.

I would also like to hide the title field in the editor.

With help from the ACF community, I have the following code which I have added to "Code Snippets" but it doesn't seem to work. Thoughts?

// run function after acf updates fields
add_action('acf/update_post', 20);
function title_from_fields($post_id) {
  // check for your post type
  if (get_post_type($post_id) != 'job-updates') {
    return;
  }
  // get the post
  $post = get_post($post_id);
  // get the taxonomy field
  $terms = get_field('job', $post_id);
  // taxonomy fields return an array, use the first term
  $term = $terms[0];
  // get date field
  $date = get_field('date', $post_id);
  // set post title/slug
  $title = $term->name.' '.$date;
  $post->post_title = $title;
  $post->post_name = sanitize_title($title);
  // remove this filter to prevent infinite loop
  remove_filter('acf/update_post', 20);
  // update the post
  wp_update_post($post);
  // re-add this filter
  add_action('acf/update_post', 20);
}

1 Answer 1

0

You can use the wordpress save_post action to update the title using the custom fields as you like. Here is the simple example I have used myself -

add_action( 'save_post', 'custom_post_type_title' );
function custom_post_type_title ( $post_id ) {
  global $wpdb;
  if ( get_post_type( $post_id ) == 'job-updates') {
    $terms = get_field('job', $post_id);
    // taxonomy fields return an array, use the first term
    $term = $terms[0];
    // get date field
    $date = get_field('date', $post_id);
    // set post title/slug
    $title = $term->name.' '.$date;
    $where = array( 'ID' => $post_id );
    $wpdb->update( $wpdb->posts, array( 'post_title' => $title ), $where );
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.