0

I'm using wordpress as a cms, so on my custom post types, I don't need the title and only use custom fields. The title however is still used, and receives the value "Auto Draft", which I don't want - even if I won't use the permalink for now.

The quickest and easiest solution would be to copy the value from my custom field "ref._nr." to the title, as this will be my unique identifier, and it will serve better in case I need to make changes later.

Unfortunately, I have no idea as to where to start with this. In case you want to contribute code, the custom post type is called "listing".

All input is much appreciated!

  • 1
    I you are going to copy ref._nr. to the title why not do away with ref._nr. and just use the title for that information? – s_ha_dum Jul 25 '13 at 16:47
  • Because the title field has some limitations, and I prefer to call everything through the same api. – WouterB Jul 25 '13 at 21:26
0

Try this:

add_action('init', 'replace_title_logic');

function replace_title_logic() {
  add_filter('wp_insert_post_data', 'replace_title_before_update', 20, 2);
  add_action('wp_insert_post', 'replace_title_after_save', 20, 2);
  add_filter('wp_insert_post_empty_content', 'allow_empty_content_for_listing', 20 , 2);      
}

function replace_title_before_update( $data, $postarr ) {
  if ( is_int($postarr['ID']) && ($data['post_type'] == 'listing') ) {
    $custom = get_post_meta($postarr['ID'], 'ref._nr.', true );
    if ( $custom && ( $custom != $data['post_title'] ) ) $data['post_title'] = $custom;
  }
  return $data;
}

function replace_title_after_save( $post_ID, $post ) {
  if ( $post->post_type != 'listing' )  return;
  $custom = get_post_meta($post_ID, 'ref._nr.', true );
  if ( $custom && ( $custom != $post->post_title ) && $post->post_status != 'trash') {
    remove_action('wp_insert_post', 'replace_title_after_save', 20, 2);
    remove_filter('wp_insert_post_data', 'replace_title_before_update', 20, 2);
    $postarr = ( array('ID' => $post_ID, 'post_title' => $custom) );
    wp_insert_post($postarr);
  }
}

function allow_empty_content_for_listing( $maybe_empty, $postarr ) {
  if ( $postarr['post_type'] == 'listing' ) return false;
}

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.