Hi there i make meta box with jQuery in wordpress. I am trying to add more than one meta boxes with jQuery.
It works all perfectly, it add meta fields and save data, remove meta fields and remove data.
but the issue is that the remove button is also shown on first (default) meta filed, when i click on remove, it remove first (default) meta field, i dont want remove button on First row.
And second issue is, when i remove the field and update the post the data in this meta field is delete but the meta field does not rove from there
My Code:
add_action('add_meta_boxes', 'add_multiple_urls');
function add_multiple_urls($post) {
add_meta_box( 'multiple-urls-id', 'Download Links', 'repeatable_download_link', 'post', 'normal', 'default');
}
function repeatable_download_link($post) {
$repeatable_fields = get_post_meta($post->ID, 'repeatable_fields', true);
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#add-row').on('click', function() {
var row = $('.empty-row.screen-reader-text').clone(true);
row.removeClass('empty-row screen-reader-text');
row.insertBefore('#repeatable-fieldset-one tbody>tr:last');
return false;
});
$('.remove-row').on('click', function() {
$(this).parents('tr').remove();
return false;
});
});
</script>
<table id="repeatable-fieldset-one" width="100%">
<thead>
<tr>
<th width="92%" align="left">URL</th>
<th width="8%"></th>
</tr>
</thead>
<tbody>
<?php
if($repeatable_fields ) :
foreach($repeatable_fields as $field ) {
?>
<tr>
<td>
<input type="text" class="widefat" name="url[]" value="<?php if ($field['url'] != '') echo esc_attr( $field['url'] ); else echo 'http://'; ?>" />
</td>
<td><a class="button remove-row" href="#">Remove</a></td>
</tr>
<?php
}
else :
// show a blank one
?>
<tr>
<td><input type="text" class="widefat" name="url[]" value="http://" /></td>
</tr>
<?php endif; ?>
<!-- empty hidden one for jQuery -->
<tr class="empty-row screen-reader-text">
<td><input type="text" class="widefat" name="url[]" value="http://" /></td>
<td><a class="button remove-row" href="#">Remove</a></td>
</tr>
</tbody>
</table>
<p><a id="add-row" class="button" href="#">Add another</a></p>
<?php
}
add_action('save_post', 'save_multiple_download_link');
function save_multiple_download_link() {
global $post;
$old = get_post_meta($post->ID, 'repeatable_fields', true);
$new = array();
$urls = $_POST['url'];
$count = count( $urls );
for($i = 0; $i < $count; $i++ ) {
if($urls[$i] == 'http://' ){
$new[$i]['url'] = '';
}
else{
$new[$i]['url'] = stripslashes( $urls[$i] ); // and however you want to sanitize
}
}
if(!empty($new) && $new != $old)
update_post_meta($post->ID, 'repeatable_fields', $new);
elseif(empty($new) && $old)
delete_post_meta($post->ID, 'repeatable_fields', $old);
}
?>
<tr><td><input type="text" class="widefat" name="url[]" value="http://" /></td></tr>After updating post, you need to remove those that are not submitted. Else, it will still be in$repeatable_fields.