Skip to content

Instantly share code, notes, and snippets.

@mapsam
Created November 18, 2014 21:12
Show Gist options
  • Save mapsam/113301ec4263321c5a10 to your computer and use it in GitHub Desktop.
Save mapsam/113301ec4263321c5a10 to your computer and use it in GitHub Desktop.
wordpress return post data on click
jQuery(document).ready(function($) {
$('.post').on('click', function(){
getPostInfo($(this).attr('data-postid'));
});
});
function getPostInfo(id) {
jQuery.ajax({
url: ajaxurl,
dataType: 'json',
data: {
action: 'postdata',
data: id
},
type: 'GET',
success: returnData
});
}
function returnData(res) {
console.log(res);
}
<?php
add_action( 'wp_ajax_postdata', 'prefix_ajax_postdata' );
add_action( 'wp_ajax_nopriv_postdata', 'prefix_ajax_postdata' );
function prefix_ajax_postdata() {
$postID = intval($_GET['data']);
$postdata = get_post($postID);
echo json_encode($postdata);
die();
}
<script type="text/javascript">var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";</script>
<?php
$posts = get_posts();
foreach ($posts as $p) :
echo '<article class="post" id="'.$p->post_name.'" data-postid="'.$p->ID.'">.$p->post_title.'</article>';
endforeach;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment