Skip to content

Instantly share code, notes, and snippets.

@mohammadmursaleen
Last active September 6, 2016 05:52
Show Gist options
  • Save mohammadmursaleen/ee2ea0723d535034f2cd to your computer and use it in GitHub Desktop.
Save mohammadmursaleen/ee2ea0723d535034f2cd to your computer and use it in GitHub Desktop.
WordPress Ajax code to add emails in post meta with postid in front end
<?php
/********************************************************************************/
/*** WordPress Ajax code to add emails in post meta with postid in front end ***/
/********************************************************************************/
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
}
@mohammadmursaleen
Copy link
Author

You can add anything in post meta with post id in ajaxified fashion using this method with some modification. Hope this would help some one in community.

@MuhammadRehman
Copy link

Hi! great post .. very helpful..

Thanks.. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment