In my custom post-type, I am building an multi dimensional array meta-box with multiple input
s, with below code:
<?php
$services = get_post_meta($post->ID, 'services', true);
foreach ((array) $services as $service) {
echo '<div class="inside">
<div>
<label>Title</label>
<input type="text" name="service[][title]" value="' . $service['title'] . '">
</div>
<div>
<label>Type</label>
<input type="text" name="service[][type]" value="' . $service['type'] . '">
</div>
<div>
<label>Content</label>
<textarea name="service[][text]">' . $service['text'] . '</textarea>
</div>';
}
exit;
?>
And, saving the data with below function:
function service_save_meta_box_data($post_id) {
// verify taxonomies meta box nonce
if (!isset($_POST['service_meta_box_nonce']) || !wp_verify_nonce($_POST['service_meta_box_nonce'], basename(__FILE__))) {
return;
}
// return if autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (!current_user_can('edit_post', $post_id)) {
return;
}
// store custom fields values
// Feature Title
if (isset($_REQUEST['services'])) {
update_post_meta($post_id, 'services', sanitize_text_field($_POST['service']));
}
}
add_action('save_post_service', 'service_save_meta_box_data');
However, the data is not being stored and retrieved in the input
s. Where am I doing the mistake?
You can use this code
Template
<?php /*
Template Name: Customform
*/
get_header()
?>
<form id="Customform">
<div class="inside">
<div>
<label>Title</label>
<input type="text" name="service[][title]" >
</div>
<div>
<label>Type</label>
<input type="text" name="service[][type]">
</div>
<div>
<label>Content</label>
<input type="hidden" name="action" value="get_data">
<textarea name="service[][text]"></textarea>
</div>
<div>
<input type="button" id="test" value="send">
</div>
</form>
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery("#test").click(function(){
console.log("test");
jQuery.ajax({
type : "POST",
dataType : "json",
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : jQuery("#Customform").serialize(),
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
});
})
</script>
<?php get_footer();?>
Functions.php
function savemyformdata() {
update_post_meta(34, 'services', $_POST['service']);
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'savemyformdata' );