Last active
August 29, 2015 14:06
-
-
Save jlittlejohn/43ce399a2b2dc0b5351a to your computer and use it in GitHub Desktop.
WP: Ajax Call to Custom Post Type
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
// Add to head tag in template | |
<script> | |
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; | |
</script> | |
// Ajax Function for Returning Custom Post Type of Glossary | |
function test_ajax() { | |
header( "Content-Type: application/json"); | |
$glossary_term = $_POST['term']; | |
global $wpdb; | |
$postid = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s",$glossary_term)); | |
$post = get_post( $postid ); | |
setup_postdata($post); | |
//Return response as an array. This will give us data.title and data.content browser-side. | |
$response = array(); | |
$response['title'] = get_the_title($post); | |
$response['content'] = get_the_content($post); | |
echo json_encode($response); | |
die(); | |
} | |
add_action("wp_ajax_nopriv_test_ajax", "test_ajax"); | |
add_action("wp_ajax_test_ajax", "test_ajax"); | |
// Perform Ajax Request on Click | |
$(".main-content").on("click", "#glossary-term", function (e) { | |
var $this = $(this); | |
e.preventDefault(); | |
var glossaryTerm = $(this).attr('data-term'); | |
console.log($this.attr("data-content")); | |
if (!$this.attr("data-content")) { | |
var response = $.ajax({ | |
type: "POST", | |
url: ajaxurl, | |
dataType: "json", | |
data: { | |
action: "test_ajax", | |
term: glossaryTerm | |
} | |
}); | |
response.done(function(data, textStatus, jqXHR) { | |
$this.attr("title", data.title); | |
$this.attr("data-content", data.content.replace(/(<([^>]+)>)/ig,"")); | |
$this.popover(); | |
$this.popover('show'); | |
}); | |
response.fail(function(jqXHR, textStatus, error) { | |
console.log("AJAX REQUEST FAILED"); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment