I’m creating a wordpress plugin, with a custom post type and in that post type a custom meta box.
Inside the meta box, I have a form that let’s the user input: Date, Media, Title.
The form looks like this:
$mc_date = get_post_meta($_GET['post'],'mc_date',true);
$mc_media = get_post_meta($_GET['post'],'mc_media',true);
$mc_title = get_post_meta($_GET['post'],'mc_title',true);
echo '<form id="add_media_form">';
echo '<table>';
echo '<tr>';
echo '<td>Date</td><td>Media</td><td>Title</td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="text" name="mc_date" value="'.$mc_date.'" class="datepicker"/></td>';
echo '<td><input type="text" name="mc_media" value="'.$mc_media.'" /></td>';
echo '<td><input type="text" name="mc_title" value="'.$mc_title.'" /></td>';
echo '<td><a href="#" class="add_new_media" rel="'.WP_PLUGIN_URL.'/mc"><img src="'.WP_PLUGIN_URL.'/mc/plus.png" /></a></td>';
echo '</tr>';
echo '</table>';
echo '</form>';
echo '<div class="addmedianotify"></div>';
jquery:
jQuery('.add_new_media').click(function(e){
var plug = jQuery(this).attr('rel');
e.preventDefault();
jQuery.post(plug + '/ajax_add_media.php',jQuery('#add_media_form').serialize(),function(data){
jQuery('.addmedianotify').html('<span>'+data+'</span>');
});
});
What I want to do, is that when the user click the ‘add_new_media’ link/image a new set of textboxes for date, media and title will appear.
My main concern is that, what’s the trick to name those inputs which is dynamic. and to save and retrieves the custom data in it.
Because the page will still update when the user clicks ‘Update’ you would need to be able to save your fields on save_post and in your ajax. Using ajax for this might not be the best method as you’re making more work for yourself by needing to save that data twice. I would ditch the ajax and simply use an html array so you can add on fields and make one submission when the user clicks ‘Update’. To add new rows as the user needs, I would simply clone your tr and append it to the table in your click event. Something like…
The PHP & HTML
The Javascript
The PHP upon form submission