I want to retrieve the content with the specific ID via ajax post method.
For instance, if I click a link tag which has a specific post ID, the content of that ID will load into the post-data div.
I am very new to wp ajax and could someone help me to achieve this?
Here is my codes
HTML a tag
<a id="<?php the_ID(); ?>" href="#">This is link</a>
<!-- the content -->
<div id="post-data"></div>
Jquery Ajax
$("a").click(function (event) {
var post_ID = $(this).attr('id');
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: "POST",
action: "my_custom_data",
data: {post_link: post_ID},
success: function (response) {
console.log(response);
$('#post-data').append(response);
}
});
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
WP Action
add_action('wp_ajax_my_custom_data', 'my_custom_data');
add_action('wp_ajax_nopriv_my_custom_data', 'my_custom_data');
function my_custom_data(){
$post_link = data['post_link'];
echo get_the_content($post_link);
die();
}
I think something is wrong with my codes, I just get the response 0.