dongshao8125
2018-08-16 08:49
浏览 73
已采纳

如何在wordpress插件中保存自定义元框中的多个复选框值?

Yes I know there is another related question which has been answered but I don't understand how to implement that solution in my code. I'm just a beginner, help me out. I want to save multiple checkbox values in custom metabox in a WordPress plugin. When user saves the post or updates it, the values of the checked checkboxes should be saved.

function cd_meta_box_cb($post){
global $post;
echo'<b> Select the contributors that have contributed to this post: </b>';
echo '<br><br>';   
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
global $wpdb;
$authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users 
ORDER BY user_nicename");
$i=0;
$n=count($authors);
foreach($authors as $author) {
    echo"<input type='checkbox' id='my_meta_box_check' 
    name='my_meta_box_check'";
    echo"value=";
    the_author_meta('user_nicename', $author->ID);
    echo">";
    echo"<label for='author'.$i>";
    the_author_meta('user_nicename', $author->ID);
    echo"</label>";
    echo "<br />";
  }

 echo"<input type='submit' id='submit_btn' name='submit' value='Submit'>";
  }
//save custom data when our post is saved
 function save_custom_data($post_id) 
 {  
  global $post;
  $contributor=get_post_meta($post->ID,'my_meta_box_check',true);
  if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;     

 if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( 
 $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
if ( isset($_POST['my_meta_box_check']) ) 
{        

    $data=serialize($_POST['my_meta_box_check']);   
    update_post_meta($post_id, 'my_meta_box_check',$data);      
 } 
else {
    delete_post_meta($post_id, 'my_meta_box_check');
 } 
}
add_action( 'save_post', 'save_custom_data' );
function displaymeta()
{

    global $post;
    $m_meta_description = get_post_meta($post->ID, 'my_meta_box_check', 
  true);
    echo 'Meta box value: ' . unserialize($m_meta_description);
}

add_filter( 'the_content', 'displaymeta' );

?>
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtun4268 2018-08-16 11:02
    已采纳

    mention checkbox field name as array like my_meta_box_check[]

    Please use the code below

    <input type='checkbox' id='my_meta_box_check' 
    name='my_meta_box_check[]'" >
    

    Please try this and check if it works for you.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题