Iâm adding custom meta-box, by means of jquery I can create in it several custom fields with a key âtestâ. There can be one or several custom fields, but the key is only âtestâ. I can also delete key values, which are no longer required. The problem is that I canât save several values of the custom field with the same key. Only the last value is saved in all the fields. Help me, please, to find a decision!
<?php add_action( 'add_meta_boxes', 'add_test_meta_box' );
function add_test_meta_box()
{
add_meta_box( 'test_meta_box', 'TEST PARAM', 'add_test_meta', 'post', 'normal', 'high' );
}
function add_test_meta( $post )
{
// Grab our data to fill out the meta boxes (if it's there)
$test = get_post_meta( $post->ID, 'test', true );
// Add a nonce field
wp_nonce_field( 'save_test_meta', 'test_meta' );
?>
<div id="myfor">
<p>
<label>Param 1 key "test" </label><br >
<input type="text" name="test" value="<?php echo esc_attr( $test ); ?>" size="60" /><span>Delete</span>
</p>
</div>
<input type="button" value="ÐобавиÑÑ" id="addnew">
<?php
}
add_action( 'save_post', 'test_meta_save' );
function test_meta_save( $id )
{
// No auto saves
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// Check our nonce
if( !isset( $_POST['test_meta'] ) || !wp_verify_nonce( $_POST['test_meta'], 'save_test_meta' ) ) return;
// make sure the current user can edit the post
if( !current_user_can( 'edit_post' ) ) return;
// strip all html tags and esc attributes here
if( isset( $_POST['test'] ) )
update_post_meta( $id, 'test', esc_attr( strip_tags( $_POST['test'] ) ) );
}
add_action('admin_head', 'my_add_input');
function my_add_input() { ?>
<script>
// add live metod
jQuery.fn.live = function (types, data, fn) {
jQuery(this.context).on(types,this.selector,data,fn);
return this;
};
// add new input
(function($){
$(function(){
var num = 2;
$('#addnew').click(function(){
$('#myfor').append('<p><label>Param '+ num +' key "test" </label><br ><input type="text" name="test" value="" size="60" /> <span>Delete</span></p>');
num ++;
});
$('span').live( 'click' , function(){
$(this).parent('p').remove();
});
});
})(jQuery)
</script>
<?php } ?>
First, dd this code [] at the end of your form field name. So your field’s name will be “test[]”.
Example:
Use this way to save the value:
Showing your field with the saved values: