Using a Custom Field instead of original title field but only for Custom Post Type

The solution you are working on will always represent multiple database inserts as the post will be saved and then the the title re-saved in a second database write. That is the nature of the save_post hook, since it runs after the primary post save.

Additionally, the code you found is wildly overcomplicated.

Interestingly, the OP in the forum you linked to was on the right track in the opening post and was then misdirected, in my opinion, to a less optimal solution, which unfortunately you’ve followed.

The hook you should be using is wp_insert_post_data. That hook allows you to alter the post data before the initial save, which saves you a database write. The performance difference isn’t going to be that much in most cases but little bits adds up and why do it second rate when first rate isn’t that hard?

function meta_value_title_wpse_126764($data){
  global $_POST;
  if ('your-cpt' = get_post_type() && !empty($_POST['meta'])) {
    foreach ($_POST['meta'] as $v) {
      if ('meta_title' == $v['key']) {
        $data['post_title'] = wp_kses( $v['value'] ); // The custom content
      }
    }
  }
//   var_dump($_POST,$data); die; // debugging
  return $data; 
}
add_action('wp_insert_post_data','meta_value_title_wpse_126764',1);

This is nearly the same answer as here and has the same caveats:

  1. I can’t remember at which step WordPress applies its own filters, so I applied wp_kses
  2. Item #1 may be overkill
  3. Item #1 may not be the particular validation function you want
  4. If there are multiple custom meta fields with the same key– article_content— the last one, and only the last one, will be used.

Leave a Comment