1

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.

  • the "action" must go in datas : "data" : {"post_link" : post_ID, "action" : "my_custom_data"} – mmm Oct 30 '17 at 16:46
0

I would put the action in the post data

$.ajax({
  url: "/wp-admin/admin-ajax.php",
  type:"POST",
       data: { 
       action: "my_custom_data",
       post_link: post_ID
},
success: function (response) {
        console.log(response);
        $('#post-data').append(response);
    }
});
   return false;
.....

Then use $_POST['post_link'] in your PHP

   function my_custom_data(){
       $post_link = $_POST['post_link'];
   echo get_the_content($post_link);
   die();
   }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.