I already read this question but it doesn't help me. I create metabox to connect 2 custom post type( 'author' and 'book' ) so that when user want to add a new book can choose author from metabox.
when I want to save authors of the book to db just the last author stores in db (wp_postmeta table).
here is my code
my metabox
add_action('admin_init', 'p2p2_add_author_metabox');
add_action('admin_init', 'p2p2_add_author_metabox');
function p2p2_add_author_metabox(){
add_meta_box(
'book_author',
__('نویسنده کتاب', 'bandpress'),
'p2p2_book_author_metabox',
'book',
'side',
'default',
array( 'id' => 'p2p2_author')
);
}
show in book custom post type
function p2p2_book_author_metabox($post, $args) {
wp_nonce_field( plugin_basename( __FILE__ ), 'p2p2_book_author_nonce' );
$author_id = get_post_meta($post->ID, 'p2p2_book_author', true);
echo "<p>انتخاب نویسنده کتاب</p>";
// Query the authors here
$query = new WP_Query( 'post_type=author' );
while ( $query->have_posts() ) {
$query->the_post();
$id = get_the_ID();
$input_check = "";
$cooaprate=get_field('auth-trans');
if(($cooaprate[0]=='نویسنده')){
$input_check="checked($author_id[$id][0],'yes')";
echo '<input name="save-author-to-book[]" type="checkbox"' . $input_check . ' value=' . $id ;
if (get_post_meta( $post_id, $key,$id )) {
echo " checked";
}
echo '>' . get_the_title() . '</br>';
}
}
}
save in database
add_action( 'save_post', 'p2p2_save_author_metabox' );
function p2p2_save_author_metabox( $post_id) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !isset( $_POST['p2p2_book_author_nonce'] ) )
return;
if ( !wp_verify_nonce( $_POST['p2p2_book_author_nonce'], plugin_basename( __FILE__ ) ) )
return;
if (isset($_POST['save-author-to-book'])) {
$key = 'save-author-to-book';
$values = $_POST["save-author-to-book"];
foreach ($values as $value) {
if ( get_post_meta( $post_id, $key, true ) ) { // If the custom field already has a value
update_post_meta( $post_id, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta( $post_id, $key, $value );
}
if ( !$value ) delete_post_meta( $post_id, $key ); // Delete if blank
}
}
}
I know the problem is come from if ( get_post_meta( $post_id, $key, true ) ) it overwrite same records but I really don't know how can I fix it.
any idea would be appreciated.