Created
February 18, 2016 08:39
-
-
Save rajasajidmanzoor/e7b77b1bf9952090d88a to your computer and use it in GitHub Desktop.
Wordpress Ajax code to perform any Function using Ajax Easily
This file contains hidden or 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 | |
/********************************************************************************/ | |
/*** Wordpress Ajax code to perform any Function using Ajax Easily***/ | |
/********************************************************************************/ | |
add_action( 'wp_footer', 'my_action_javascript' ); | |
function my_action_javascript() { ?> | |
<script type="text/javascript" > | |
/* Make this document ready function to work on click where you want */ | |
jQuery(document).ready(function($) { | |
/* In front end of WordPress we have to define ajaxurl */ | |
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; | |
/* You can get this value from some hidden field or div */ | |
var postid = 1; | |
/* get this email from some input field */ | |
var email = "[email protected]"; | |
var data = { | |
'action': 'my_action', | |
'email_to_add' : email, | |
'postid' : postid | |
}; | |
$.post(ajaxurl, data, function(response) { | |
alert(response); | |
}); | |
}); | |
</script> <?php | |
} | |
add_action( 'wp_ajax_my_action', 'my_action_callback' ); | |
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' ); | |
function my_action_callback() { | |
$postid = $_POST['postid']; | |
$email = $_POST['email_to_add']; | |
/* get existing emails from post meta */ | |
$prev_emails = get_post_meta($postid,'emails_to_notify',true); | |
/* get the title of post */ | |
$post_title = get_the_title($postid); | |
/* concatenate new email with previous if they exist */ | |
if($prev_emails) | |
$emails = (string) $prev_emails . ',' . (string) $email ; | |
else | |
$emails = (string) $email; | |
/* update emails in post meta */ | |
update_post_meta( $postid ,'emails_to_notify', $emails ); | |
/* send response to know what is really going on */ | |
echo " Email added to post with tiltle: ". $post_title . "\n New email added: ". $email ."\n Following emails are there: " . $emails ; | |
die(); // this is required to terminate immediately and return a proper response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment