I'm using RW_Meta_Box plugin by Rilwis.
I'm using a CPT and added a custom meta-box and removed the title
and editor
.
But I still want to set the title for some obvious reasons.
I created the CPT and meta-box and everything worked perfectly including the all posts
page using custom column
hooks.
As soon as I sat to set post title to one of the fields in the meta-box, I failed to get the desired results.I tried to solutions I picked by searching through this Q&A site.
Initially I tried:
SOLUTION1:
add_action('submitpost_box', 'hidden_type_title');
function hidden_type_title() {
global $current_user, $post, $post_type;
global $prefix;
$md = rwmb_meta($prefix . 'name', array('type' => 'text'), $post->ID);
if ($post->post_type == 'MY_CPT_NAME') {
?>
<input type="hidden" name="post_title" value="<?php echo esc_attr(htmlspecialchars($md)); ?>" id="title" />
<?php
} else {
return;
}
}
The above code works fine but it has a problem I am unable to detect. which is, I need to update the post twice to set the post title.
Therefore I went on to try the save_post
hook like so:
SOLUTION2:
add_action('save_post', 'post_updated');
function post_updated($post_id) {
global $current_user, $post;
if ($post->post_type != 'MY_CPT_NAME') {
return;
}
global $prefix;
$md = rwmb_meta($prefix . 'name', array('type' => 'text'), $post_id);
// verify post is not a revision & not an autosave
if (!wp_is_post_revision($post_id) && !(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) {
// set the new post title
$post->ID = $post_id;
$post->post_title = $md;
// update the post, removing the action to prevent an infinite loop
remove_action('save_post', 'post_updated');
wp_update_post($post);
add_action('save_post', 'post_updated');
return;
}
}
Now, I'm in a worse situation, the post title is instantly set but my meta-box data is somehow not being saved.
What might be wrong with the first solution?
echo esc_attr(htmlspecialchars($md));
won't have a value in your hidden input until you save... hence needing to save twice to set the title. What is the name of the field you want to base the post title off of?