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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀