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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 游戏盾如何溯源服务器真实ip?
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥50 win10链接MySQL
  • ¥15 抖音看过的视频,缓存在哪个文件