Created
August 9, 2012 21:04
-
-
Save trepmal/3308061 to your computer and use it in GitHub Desktop.
Checkboxes & Ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Plugin Name: Checkboxes & Ajax | |
//Description: In re to http://wordpress.stackexchange.com/questions/61390/edit-post-meta-with-checkboxes-on-front-end | |
//add our test checkboxes | |
add_filter( 'the_content', 'cba_add_checkboxes'); | |
function cba_add_checkboxes( $c ) { | |
$first = get_post_meta( get_the_ID(), 'first_item_key', true ); | |
$second = get_post_meta( get_the_ID(), 'second_item_key', true ); | |
$c .= '<p class="cba"><input type="checkbox" name="test_value_1" '. checked( $first, 'true', false ) .' /><br /> | |
<input type="checkbox" name="test_value_2" '. checked( $second, 'true', false ) .' /> | |
<input type="hidden" name="post_id" value="'. get_the_ID() .'" /><br /><span class="response"></span></p>'; | |
return $c; | |
} | |
//enqueue our scripts - this is the lazy way :( | |
//we should be properly enqueuing and localizing the scripts | |
add_action('wp_footer', 'cba_script'); | |
function cba_script() { | |
wp_enqueue_script('jquery'); | |
?><script> | |
jQuery(document).ready( function($) { | |
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>'; | |
var spinner = '<?php echo admin_url( 'images/wpspin_light.gif' ); ?>'; | |
$('.cba input').click( function() { | |
var p = $(this).parent('p'); | |
p.find('.response').html('<img src="'+spinner+'" />'); | |
$.post(ajaxurl, { | |
'action': 'update_custom_fields', | |
'post_id': p.find('input[name="post_id"]').val(), | |
'first_item': p.find('input[name="test_value_1"]').is(':checked'), | |
'second_item': p.find('input[name="test_value_2"]').is(':checked') | |
}, function( response ) { | |
p.find('.response').html(response); | |
}, 'text'); | |
}); | |
}); | |
</script><?php | |
} | |
//hook into the ajax api | |
add_action( 'wp_ajax_update_custom_fields', 'cba_update_custom_fields' );//for logged-in users | |
add_action( 'wp_ajax_nopriv_update_custom_fields', 'cba_update_custom_fields' );//for logged-out users | |
function cba_update_custom_fields() { | |
$post_id = $_POST[ 'post_id' ]; | |
$first_item = $_POST[ 'first_item' ]; | |
$second_item = $_POST[ 'second_item' ]; | |
update_post_meta( $post_id, 'first_item_key', $first_item ); | |
update_post_meta( $post_id, 'second_item_key', $second_item ); | |
//this message is sent back and displayed as the confirmation message | |
//we should probably also have an error message in here | |
die('Updated'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment