Skip to content

Instantly share code, notes, and snippets.

@badcrocodile
Last active November 5, 2020 20:33
Show Gist options
  • Save badcrocodile/e5d08fb6b9c60a9942a8a037bf32a9be to your computer and use it in GitHub Desktop.
Save badcrocodile/e5d08fb6b9c60a9942a8a037bf32a9be to your computer and use it in GitHub Desktop.
<?php
add_action('wp_ajax_addTagToStory', 'add_tag_to_story');
add_action('wp_ajax_nopriv_addTagToStory', 'add_tag_to_story');
function add_tag_to_story() {
// Here you have everything passed from your JS function available as $_POST
// With $_POST['postID'], you can do almost any post manipulation you need
var_dump($_POST);
if(validate_nonce($_POST['nonce'], 'iwt_add_tag_to_post_' . $_POST['postID']) {
wp_set_post_terms( $_POST['postID'], 'my_new_tag_slug', 'tag', false );
echo "<div class='alert alert-success'>Successfully added tag to post!</div>";
die(); // important!
} else {
// nonce failed, send error message
echo "<div class='alert alert-danger'>Nonce validation failed, please try again</div>";
die();
}
}
function create_nonce($nonce_string = 'iwt-nonce') {
return wp_create_nonce($nonce_string);
}
function validate_nonce($nonce, $nonce_string = 'iwt-nonce') {
if (!wp_verify_nonce($nonce, $nonce_string)) {
// This nonce is not valid.
return false;
} else {
// The nonce was valid.
return true;
}
}
?>
<?php
$args = [
'post_type' => 'story',
'posts_per_page' => 10,
'orderby' => 'title',
'order' => 'ASC'
];
$query = new WP_Query($args); ?>
<?php if($query->have_posts()) : while($query->have_posts()) : $query->the_posts(); ?>
<div id="post-<?= get_the_ID() ?>" class="append-our-message-here">
<h1><?= get_the_title() ?></h1>
<a href="javascript:;" class="click-me-to-add-tag" data-id=<?= get_the_ID() ?> data-nonce=<?= create_nonce('iwt_add_tag_to_post_' . get_the_ID()) ?>>Click me to add a tag with AJAX</a>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
(function($) {
$(document).ready(function() {
addTagToStory();
});
function addTagToStory() {
var actionButton = $('.click-me-to-add-tag');
$(actionButton).on('click', function(e) {
e.preventDefault();
console.log("Running thingy");
var postID = $(this).data('id');
var nonce = $(this).data('nonce);
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
dataType: 'json',
'action': 'add_tag_to_story',
'postID': postID,
'nonce': nonce
},
beforeSend: function () {
},
complete: function () {
},
success: function (data) {
// Do your front-end stuffs here, like adding a "Success" message or a spiny wheel or whatever
// data is whatever was returned by the php function
console.log(data);
// This should append our alert to the DIV
$('#post-' + $_POST['postID']).fadeOut().append(data).fadeIn();
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment