Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

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.

share|improve this answer
    
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 Jul 17 '11 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 Jul 17 '11 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 Jul 17 '11 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 Jul 17 '11 at 15:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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