In your save_post action hook you will get the input from the metabox in the global $_POST. For example, if your input field has the name="tagsuggester"
, in the save function you will get its value in $_POST['tagsuggester']
. Once you get this value you can update the post tags by using wp_set_object_terms() function. But note that using your code you can have several input elements with the same name attribute and this will make that you don’t get all values in the global $_POST. Also, you don’t have any call to the function to add and display the custom metabox.
Here an example code:
//Add meta boxes to handle your custom fields
add_action('add_meta_boxes', 'tagsuggester_post_meta');
function tagsuggester_post_meta(){
add_meta_box("post", __( 'Tags suggestion' ), "tagsuggester_display_meta_box", 'post', "normal", "high",array());
}
//The callback function to display the metabox added in previous function
function tagsuggester_display_meta_box($post){
//nonce field for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'tagsuggester_plugin_noncename' );
//Current post tags
$tags = wp_get_post_tags();
//Your code to suggest meta tags
$title = get_the_title();
$title_array = explode(' ', $title);
foreach( $title_array as $word ) {
//var_dump( $word );
$word_length = strlen($word);
if ( $word_length > 3 ) {
//echo $word;
//Note the [] in the name to make an array of inputs
echo '<input type="checkbox" name="tagsuggester[]" value="'.$word.'"> '.$word.'</br>';
}
}
}
//Save action hook
add_action( 'save_post', 'tagsuggester_save_postdata' );
function tagsuggester_save_postdata($post_id){
// First we need to check if the current user is authorised to do this action.
if ( isset($_POST['post_type']) && 'post' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_post', $post_id ) ) return;
}
// Secondly we need to check if the user intended to change this value.
if ( !isset( $_POST['tagsuggester_plugin_noncename'] ) || ! wp_verify_nonce( $_POST['tagsuggester_plugin_noncename'], plugin_basename( __FILE__ ) ) )
return;
// Thirdly we can save the value to the database updating the tags
if(!empty($_POST['tagsuggester'])){
wp_set_post_terms( $post_id, $_POST['tagsuggester'], "post_tag" );
}
}