I'm trying to use Ajax from within the Wordpress edit post section. I want to create a button that adds a new text box.
I want to use ajax so that when the use clicks the 'Add new' button it addes a number to an array using array_push & then foreach to display a text box for each array value. Anyone have any insight? Here's the code:
add_action('admin_head', 'slideshow_meta_box_head');
add_action('wp_ajax_slideshow_ajax_data_save', 'slideshow_save_ajax');
function slideshow_meta_box_head() {
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery('form#slideshow_save').submit(function() {
var image = jQuery(this).serialize();
jQuery.post(ajaxurl, image);
return false;
});
});
</script>
}
function slideshow_ajax_data_save() {
unset($_REQUEST['action']);
}
function slideshow_meta_box() {
global $post;
$meta_box_value = get_post_meta($post->ID, 'slideshow', true);
$options = explode(",", $meta_box_value);
<form id="slideshow_save">
<input type="hidden" name="slideshow_noncename" id="slideshow_noncename" value="<?php echo wp_create_nonce('slideshow_nonce'); ?>" /><?php
$values = array('0');
foreach($values as $value) { ?>
<div style="position: relative; margin: 10px 10px 0 0;">
<input type="text" id="Image" style="position: relative; right: 0; width: 85%;" name="slideshow[<?php echo $value; ?>]" value="<?php echo $options[$value]; ?>" />
</div>
<?php } ?>
<input type="hidden" name="action" value="slideshow_save_ajax" />
<input type="submit" value="Add new" />
</form><?php
}
function slideshow_create_box() {
global $theme_name;
if ( function_exists('add_meta_box') ) {
add_meta_box( 'slideshow-meta-box', 'Slideshow Image', 'slideshow_meta_box', 'post', 'side', 'high' );
}
}
function slideshow_save_postdata ($post_id) {
global $post;
if (!wp_verify_nonce($_POST['slideshow_noncename'], 'slideshow_nonce' )) {
return $post_id;
}
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
}
else {
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
}
$array = $_POST['slideshow'];
$data = implode(",", $array);
if(get_post_meta($post_id, 'slideshow') == '')
add_post_meta($post_id, 'slideshow', $data, true);
elseif($data != get_post_meta($post_id, 'slideshow', true))
update_post_meta($post_id, 'slideshow', $data);
elseif($data == '')
delete_post_meta($post_id, 'slideshow', get_post_meta($post_id, 'slideshow', true));
}
add_action('admin_menu', 'slideshow_create_box');
add_action('save_post', 'slideshow_save_postdata');