0

I am trying to create a plugin that can relate two posts to each other, and to do so I am trying to use AJAX, but I am having trouble getting the current posts ID using $post->ID.

I am trying to relate custom post types that I created to each other, and when I tested the AJAX it worked flawlessly.

here is the code,

function eu_database_return(){

    global $wpdb;
    global $post;

    if(isset($_POST)){
        //insert the relation into the database
        $wpdb->insert('eu_relations', array('id' => NULL, 'item_id' => $post->ID, 'related_item_id' => $_POST['post_id']));
    }

    echo 'added into the database';

    die();
}

that is my AJAX function to save the data into the database, any idea what I am doing wrong?

1 Answer 1

4

If I understand correctly- this is an AJAX request, there is no $post var because you haven't loaded anything from the database in this request. You have to pass both the ID you want to relate it to, and also the ID you want to relate it from, neither exist in the current request.

4
  • I have added a meta box and I am listing all of the posts in a select list, and I am assigning the post ID to the id attribute in the loop I use to generate the select list, I then get the posts ID from the id attribute set in the select list on each option using jQuery, so I have the ID of the post I want to relate the current page to, but I still need the current pages ID. I am still quite new to wordpress AJAX, how can I get the current page's ID?
    – Odyss3us
    Commented Jul 17, 2011 at 11:08
  • You have to grab it with jQuery and pass it the same way. there's a form on the post edit screen with a hidden input element with ID of post_ID which will contain the post's ID
    – Milo
    Commented Jul 17, 2011 at 14:21
  • 1
    Another option is to use wp_localize_script, which will let you pass data to your ajax script when you enqueue it. You could set a javascript variable at that point which contained the post ID you are currently loading, so when you went to make your ajax call, the javascript var is already set and ready to pass.
    – Milo
    Commented Jul 17, 2011 at 14:30
  • Yeah I saw that hidden field, but I wasn't too sure if that would be the best way to go about it, I was kinda saving it as a last resort if all else failed, but I'll give the wp_localize_script function a go now and see what happens! Thanx a lot!
    – Odyss3us
    Commented Jul 17, 2011 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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